-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTree.cpp
111 lines (99 loc) · 1.86 KB
/
BinaryTree.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
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
104
105
106
107
108
109
110
111
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node* left, * right;
};
Node* NewNode(int data)
{
Node* node = new Node;
if(!node)
{
cout << "Error\n";
return NULL;
}
node->data = data;
node->left = node->right = NULL;
return node;
}
Node* InsertLevelOrder(int arr[], int i, int n)
{
Node* root = nullptr;
if(i < n)
{
root = NewNode(arr[i]);
root->left = InsertLevelOrder(arr, 2*i+1, n);
root->right = InsertLevelOrder(arr, 2*i+2, n);
}
return root;
}
Node* InsertNode(Node* root, int data)
{
if(root == NULL)
{
root = NewNode(data);
return root;
}
queue<Node*> q;
q.push(root);
while(!q.empty())
{
Node* temp = q.front();
q.pop();
if(temp->left != NULL)
{
q.push(temp->left);
} else {
temp->left = NewNode(data);
return root;
}
if(temp->right != NULL)
{
q.push(temp->right);
} else
{
temp->right = NewNode(data);
return root;
}
}
return NULL;
}
void InOrder(Node* root)
{
if(root != NULL)
{
InOrder(root->left);
cout << root->data << " ";
InOrder(root->right);
}
}
void PreOrder(Node* root)
{
if(root != NULL)
{
cout << root->data << " ";
PreOrder(root->left);
PreOrder(root->right);
}
}
void PostOrder(Node* root)
{
if(root != NULL)
{
PreOrder(root->left);
PreOrder(root->right);
cout << root->data << " ";
}
}
int main()
{
int arr[] = { 8, 6, 7, 12, 5, 1, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
Node* root = InsertLevelOrder(arr, 0, n);
InOrder(root);
cout << endl;
PreOrder(root);
cout << endl;
PostOrder(root);
}