本文研究先序遍歷的方式建立二叉樹,打印二叉樹(遞歸方式)
首先是,先序遍歷建立二叉樹。
輸入:014xx5xx2x6xx
(1)接受輸入元素element,建立一個新的節點,若該節點爲第一個節點,則將樹root指針指向它(這個也不需要,只要遞歸開始的時候,將root傳進去,root會改變指向,root->left也會)
(2)遞歸處理左右子樹,結束遞歸的條件是輸入爲x,要向下一級遞歸傳遞一個當前根節點的指針,以建立連接關係,不用,因爲創建的時候,p->left就是指向創建的節點
遞歸結束的條件是:當前子樹爲空
遞歸核心處理操作:動態創建一個節點,賦值。。
寫遞歸算法的要義是:不要管遞歸結束太細節的條件,關注每一次遞歸實現的處理,以及這些處理間的順序
核心代碼:
typedef struct node
{
int data;
struct node *left;
struct node *right;
}*BTree;
int TreeCreat_preorder(BTree &root)
{
int ch;
if((ch=getchar())!='x')
{
root = (struct node*)malloc(sizeof(struct node));
root->data = ch-'0';
TreeCreat_preorder(root->left);
TreeCreat_preorder(root->right);
}
}
int TreePrint_preorder(BTree root)
{
if(root)
{
printf("%d ",root->data);
TreePrint_preorder(root->left);
TreePrint_preorder(root->right);
}
}
現在的一點問題是:沒有提供輸入異常檢測機制
OVER!!!