二叉树的创建,遍历完整代码

 1 #include 
 2 #include 
 3 
 4 typedef struct TreeNode{
 5     int value;
 6     struct TreeNode* Left;
 7     struct TreeNode* Right;
 8 }TreeNode;
 9 
10 void printTree(TreeNode* T, int depth);
11 
12 TreeNode *CreatTree()
13 {
14     TreeNode * T = (TreeNode*)malloc(sizeof(TreeNode));
15     int val;
16     scanf_s("%d", &val);
17     if (val == 0)
18         return NULL;
19     T->value = val;
20     T->Left = T->Right = NULL;
21     T->Left = CreatTree();
22     T->Right = CreatTree();
23     
24     return T;
25     
26 }
27 
28 void InOrderTraversal(TreeNode* T, int depth)
29 {
30     if (T)
31     {
32         InOrderTraversal(T->Left, depth + 1);
33         printTree(T, depth);
34         InOrderTraversal(T->Right, depth + 1);
35     }
36 }
37 
38 void printTree(TreeNode* T, int depth)
39 {
40     while (depth--)
41         printf("  ");
42     printf("%d\n", T->value);
43 }
44 
45 int main()
46 {
47     TreeNode *T ;
48     T = CreatTree();
49     InOrderTraversal(T, 0);
50 
51     return 0;
52 }

 

转载于:https://www.cnblogs.com/hi3254014978/p/9519833.html

你可能感兴趣的:(二叉树的创建,遍历完整代码)