二叉树的创建

二叉树的抽象数据类型:

1 typedef  char DataType;
2 typedef struct Node
3 {
4     DataType data;
5     struct Node* Lchild;
6     struct Node* Rchild;
7 }BTNode;//Binary Tree Node

创建二叉树:

 1 BTNode* CreateBinaryTree()
 2 {/*按先序遍历创建二叉链表*/
 3     char ch = '\0';
 4     BTNode* root;
 5     static flag = 1;
 6 
 7     if (flag)
 8     {//只在函数开始打印提示语句,递归时不打印
 9         printf("请输入该二叉树先序遍历序列(用^表示空子树,叶子结点要跟两个^):\n");
10         flag = 0;
11     }
12 
13     ch = getchar();
14     if (ch == '^')
15     {
16         return NULL;
17     }
18     else
19     {
20         root = (BTNode*)calloc(1, sizeof(BTNode));
21         root->data = ch;
22         root->Lchild = CreateBinaryTree();
23         root->Rchild = CreateBinaryTree();
24     }
25     return root;
26 }
View Code

打印二叉树:

 1 void PrintBinaryTree(BTNode* root, int h)
 2 {/*按树状打印二叉树,设置表示结点层次的参数 h ,以控制结点输出时的左右位置*/
 3     int i = 0;
 4 
 5     if (root == NULL)
 6     {
 7         return;
 8     }
 9     else
10     {
11         PrintBinaryTree(root->Rchild, h + 1);
12         for (i = 0; i < h; i++)
13         {
14             printf(" ");
15         }
16         printf("%c\n", root->data);
17         PrintBinaryTree(root->Lchild, h + 1);
18     }
19 }
View Code

源代码:

 1 #define _CRT_SECURE_NO_WARNINGS
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 
 5 typedef  char DataType;
 6 typedef struct Node
 7 {
 8     DataType data;
 9     struct Node* Lchild;
10     struct Node* Rchild;
11 }BTNode;//Binary Tree Node
12 
13 BTNode* CreateBinaryTree();
14 void PrintBinaryTree(BTNode* root, int h);
15 
16 int main(void)
17 {
18     int h = 0;
19     BTNode* A = NULL;
20 
21     A = CreateBinaryTree();
22 
23     PrintBinaryTree(A, h);
24     
25     system("pause");
26     return 0;
27 }
28 
29 BTNode* CreateBinaryTree()
30 {/*按先序遍历创建二叉链表*/
31     char ch = '\0';
32     BTNode* root;
33     static flag = 1;
34 
35     if (flag)
36     {//只在函数开始打印提示语句,递归时不打印
37         printf("请输入该二叉树先序遍历序列(用^表示空子树,叶子结点要跟两个^):\n");
38         flag = 0;
39     }
40 
41     ch = getchar();
42     if (ch == '^')
43     {
44         return NULL;
45     }
46     else
47     {
48         root = (BTNode*)calloc(1, sizeof(BTNode));
49         root->data = ch;
50         root->Lchild = CreateBinaryTree();
51         root->Rchild = CreateBinaryTree();
52     }
53     return root;
54 }
55 
56 void PrintBinaryTree(BTNode* root, int h)
57 {/*按树状打印二叉树,设置表示结点层次的参数 h ,以控制结点输出时的左右位置*/
58     int i = 0;
59 
60     if (root == NULL)
61     {
62         return;
63     }
64     else
65     {
66         PrintBinaryTree(root->Rchild, h + 1);
67         for (i = 0; i < h; i++)
68         {
69             printf(" ");
70         }
71         printf("%c\n", root->data);
72         PrintBinaryTree(root->Lchild, h + 1);
73     }
74 }
View Code

 

posted @ 2022-01-08 23:57  吕辉  阅读(46)  评论(0)    收藏  举报