-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbinarytree.c
More file actions
103 lines (93 loc) · 2.1 KB
/
binarytree.c
File metadata and controls
103 lines (93 loc) · 2.1 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <stdio.h>
struct BinaryTreeNode
{
int data;
struct BinaryTreeNode *left;
struct BinaryTreeNode *right;
};
typedef struct BinaryTreeNode BinaryTree;
BinaryTree *Insert(BinaryTree *root, int data)
{
if (root == NULL)
{
root = (BinaryTree *)malloc(sizeof(BinaryTree));
if (root == NULL)
{
printf("memory error");
return;
}
else
{
root->data = data;
root->left = root->right = NULL;
}
}
else
{
if (data < root->data)
root->left = Insert(root->left, data);
else if (data > root->data)
root->right = Insert(root->right, data);
}
}
BinaryTree *Create(int data)
{
BinaryTree *root = (BinaryTree *)malloc(sizeof(BinaryTree));
root->data = data;
root->left = NULL;
root->right = NULL;
return (root);
}
void preorder(BinaryTree *root)
{
if (root)
{
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
}
void inorder(BinaryTree *root)
{
if (root)
{
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
void postorder(BinaryTree *root)
{
if (root)
{
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
}
int main()
{
BinaryTree *root = Create(1);
root->left = Create(2);
root->right = Create(3);
root->left->left = Create(4);
root->left->right = Create(5);
root->right->left = Create(6);
root->right->right = Create(7);
/* Insert(root, 10);
Insert(root, 22\);
Insert(root, 19);
Insert(root, 31);
Insert(root, 67);
Insert(root, 9);*/
printf("Preorder traversal of the tree : \n");
preorder(root);
printf("\n");
printf("inorder traversal of the tree : \n");
inorder(root);
printf("\n");
printf("postorder traversal of the tree : \n ");
postorder(root);
printf("\n");
return 0;
}