递归创建二叉树

这里记录一下用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的信号。然后采用先序遍历的方式遍历这棵二叉树。

然后还需要注意一点,那就是输入这棵二叉树的结点的时候,我们需要先创建出这棵二叉树,然后代码里面基本上是先序的方式,因此我们就以先序的顺序输入二叉树所有的节点。

 

 

posted @ 2021-07-17 11:33  EvanTheBoy  阅读(165)  评论(0)    收藏  举报