遞迴建立二叉樹
阿新 • • 發佈:2021-07-17
這裡記錄一下用C語言遞迴建立樹的程式碼:
1 #include <stdio.h> 2 #include <assert.h> 3 struct TreeNode { 4 struct TreeNode* left; 5 struct TreeNode* right; 6 char val; 7 }; 8 9 void CreateTree(struct TreeNode** root) 10 { 11 char info = '\0'; 12 scanf_s("%c", &info, 1); 13 if(info == '#') { 14 *root = NULL; 15 } 16 else { 17 *root = (struct TreeNode*)malloc(sizeof(struct TreeNode)); 18 assert(*root); 19 (*root)->val = info; 20 CreateTree(&(*root)->left); 21 CreateTree(&(*root)->right); 22 } 23 }24 25 void preOrder(struct TreeNode* root) 26 { 27 if (root) { 28 printf("%c ", root->val); 29 preOrder(root->left); 30 preOrder(root->right); 31 } 32 } 33 34 int main() 35 { 36 struct TreeNode* root = NULL; 37 CreateTree(&root); 38 preOrder(root);39 return 0; 40 }
這裡我們以輸入‘#’號作為該結點為NULL的訊號。然後採用先序遍歷的方式遍歷這棵二叉樹。
然後還需要注意一點,那就是輸入這棵二叉樹的結點的時候,我們需要先創建出這棵二叉樹,然後程式碼裡面基本上是先序的方式,因此我們就以先序的順序輸入二叉樹所有的節點。