一、前序遍歷創建二叉樹,使用遞歸,頭文件 BiTree.h
/*槽點一:創建樹時用scanf輸入不成功*/ #ifndef BITREE_H #define BITREE_H #include<stdio.h> #include<stdlib.h> typedef char ElementType; typedef struct treenode { ElementType data; struct treenode *leftchild; struct treenode *rightchild; } TreeNode; /*使用先序遍歷創建二叉樹*/ TreeNode *create_bitree() { ElementType ch; TreeNode *T; scanf("%c",&ch); //這樣調用scanf時,樹的結點一次全部輸入,如果要一次一個的輸入,在%c前加個空格 if(ch!='#') { T=(TreeNode*)malloc(sizeof(TreeNode)); T->data=ch; T->leftchild=create_bitree(); T->rightchild=create_bitree(); } else { T=NULL; } return T; } /*先序遍歷*/ void pre_order_traversal(TreeNode *T) { ElementType data; if(T!=NULL) { data=T->data; printf("%c ",data); pre_order_traversal(T->leftchild); pre_order_traversal(T->rightchild); } } #endif
有兩個地方需要注意:1、要將樹的節點指針作為返回值返回,而不能向下面這樣直接作為參數傳入,因為作為參數傳遞時只是傳遞了T 的一個copy,后來調用malloc函數分配新的內存地址時,也是賦給了這個備份,也就是說最后T依然沒有改變,碰到malloc和指針做參數都要注意這個問題;2、scanf函數的問題:scanf會讀入回車符,當需要一個一個的輸入字符時,可以在%c前面加個空格
int create_bitree(TreeNode *T;) { ElementType ch; scanf("%c",&ch); //這樣調用scanf時,樹的結點一次全部輸入,如果要一次一個的輸入,在%c前加個空格 if(ch!='#') { T=(TreeNode*)malloc(sizeof(TreeNode)); T->data=ch; create_bitree(T->leftchild); create_bitree(T->rightchild); } else { T=NULL; } return 1; }