-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_tree.cpp
More file actions
105 lines (89 loc) · 1.63 KB
/
binary_tree.cpp
File metadata and controls
105 lines (89 loc) · 1.63 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
104
105
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node *left, *right;
Node(int data)
{
this->data = data;
this->left = this->right = NULL;
}
};
Node *root;
Node *makeTree()
{
Node *newNode;
newNode = NULL;
return newNode;
}
void insert(int item) // iterative inserting
{
if (root == NULL)
{
root = new Node(item);
return;
}
queue<Node *> q;
q.push(root);
while (!q.empty())
{
Node *temp = q.front();
q.pop();
if (!(temp->left))
{
temp->left = new Node(item);
return;
}
else if (!(temp->right))
{
temp->right = new Node(item);
return;
}
else
{
q.push(temp->left);
q.push(temp->right);
}
}
}
void preOrder(Node *root)
{
if (!root)
return;
cout << root->data << " ";
preOrder(root->left);
preOrder(root->right);
}
void postOrder(Node *root)
{
if (!root)
return;
preOrder(root->left);
preOrder(root->right);
cout << root->data << " ";
}
void inOrder(Node *root)
{
if (!root) return;
preOrder(root->left);
cout << root->data << " ";
preOrder(root->right);
}
int main()
{
root = makeTree();
int key[10] = {1, 3, 5, 6, 8, 2, 7, 9, 4, 10};
for (int i = 0; i < 10; i++)
insert(key[i]);
cout << "Pre Order : ";
preOrder(root);
cout << endl;
cout << "Post Order : ";
postOrder(root);
cout << "In Order : ";
inOrder(root);
cout << endl;
return 0;
}