-
Notifications
You must be signed in to change notification settings - Fork 3
/
建立大根堆并打印、层序遍历.cpp
75 lines (67 loc) · 1.21 KB
/
建立大根堆并打印、层序遍历.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct Node;
typedef struct Node* PtrToNode;
typedef PtrToNode BiTree;
struct Node
{
int data;
BiTree LeftChild, RightChild;
};
BiTree CreateTree(BiTree head, int temp)
{
BiTree T = head;
if (T == NULL||T->data==0)
{
T = (BiTree)malloc(sizeof(struct Node));
T->data = temp;
T->LeftChild = NULL;
T->RightChild = NULL;
}
else
{
if (temp > T->data)
T->RightChild = CreateTree(T->RightChild, temp);
else
if (temp < T->data)
T->LeftChild= CreateTree(T->LeftChild, temp);
}
return T;
}
void PrintTree(BiTree head, int degree)
{
if (head != NULL) {
PrintTree(head->LeftChild, degree + 1);
for (int i = 0; i < degree; i++)
printf(" ");
printf("%d\n", head->data);
PrintTree(head->RightChild, degree + 1);
}
}
void PrintInOrder(BiTree head)
{
if (head != NULL) {
PrintInOrder(head->LeftChild);
printf(" %d", head->data);
PrintInOrder(head->RightChild);
}
}
int main()
{
int temp;
BiTree head = (BiTree)malloc(sizeof(struct Node));
head->data = 0;
while (1)
{
scanf("%d", &temp);
if (temp == 0)
break;
else
head = CreateTree(head, temp);
}
PrintTree(head, 0);
printf("\n");
PrintInOrder(head);
printf("\n");
}