-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrees9.c
97 lines (88 loc) · 1.74 KB
/
trees9.c
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
// Depth-first Traversal
// Time Complexity = O(n)
// Space Complexity = O(h), h=height of tree
// h
// |-> worst case: O(n)
// |-> Best/Average: O(log n)
#include <stdio.h>
#include<stdlib.h>
#include <stdbool.h>
#include "print.h"
BstNode *Insert(BstNode *root, int data);
BstNode *GetNewNode(int data);
void Preorder(BstNode *root)
{
if (root == NULL)
{
return;
}
printf("%d ", root -> data);
Preorder(root -> left);
Preorder(root -> right);
}
void Inorder(BstNode *root)
{
if (root == NULL)
{
return;
}
Inorder(root -> left);
printf("%d ", root -> data);
Inorder(root -> right);
}
void Postorder(BstNode *root)
{
if (root == NULL)
{
return;
}
Postorder(root -> left);
Postorder(root -> right);
printf("%d ", root -> data);
}
int main(void)
{
BstNode *root = NULL;
root = Insert(root, 10);
root = Insert(root, 8);
root = Insert(root, 9);
root = Insert(root, 7);
root = Insert(root, 11);
root = Insert(root, 12);
printBST(root,0);
printf("Preorder: ");
Preorder(root);
printf("\n");
printf("Inorder: ");
Inorder(root);
printf("\n");
printf("Postorder: ");
Postorder(root);
printf("\n");
return 0;
}
BstNode *Insert(BstNode *root, int data)
{
if (root == NULL)
{
root = GetNewNode(data);
return root;
}
else if(data <= root -> data)
{
root -> left = Insert(root -> left, data);
}
else
{
root -> right = Insert(root -> right, data);
}
return root;
}
BstNode *GetNewNode(int data)
{
BstNode *newNode = malloc(sizeof(BstNode));
newNode -> data = data;
newNode -> left = NULL;
newNode -> right = NULL;
return newNode;
}