-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathbinary_tree.cpp
130 lines (119 loc) · 2.4 KB
/
binary_tree.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <bits/stdc++.h>
using namespace std;
class treeNode
{
public:
int data;
treeNode* left = NULL;
treeNode* right = NULL;
treeNode( int data)
{
this->data = data;
}
~treeNode()
{
delete left;
delete right;
}
};
treeNode* takeinput()
{
int rootdata;
cout<<"enter root data: ";
cin>>rootdata;
if(rootdata == 0)
{
return NULL;
}
treeNode* root = new treeNode(rootdata);
queue<treeNode*> pendingNodes;
pendingNodes.push(root);
while(pendingNodes.size() != 0)
{
treeNode* front = pendingNodes.front();
pendingNodes.pop();
cout<<"enter left child of "<<front->data<<": ";
int lchild;
cin>>lchild;
if(lchild != 0)
{
treeNode* child = new treeNode(lchild);
front->left = child;
pendingNodes.push(child);
}
cout<<"enter right child of "<<front->data<<": ";
int rchild;
cin>>rchild;
if(rchild != 0)
{
treeNode* chil = new treeNode(rchild);
front->right = chil;
pendingNodes.push(chil);
}
}
return root;
}
void printTree(treeNode* root)
{
if(root==NULL)
{
return;
}
cout<<root->data<<": ";
if(root->left != NULL)
{
cout<<"L"<<root->left->data;
}
if(root->right != NULL)
{
cout<<" R"<<root->right->data;
}
cout<<endl;
printTree(root->left);
printTree(root->right);
}
void inorder(treeNode* root)
{
if(root==NULL)
{
return;
}
inorder(root->left);
cout<<root->data <<" ";
inorder(root->right);
}
void preorder(treeNode* root)
{
if(root==NULL)
{
return;
}
cout<<root->data <<" ";
preorder(root->left);
preorder(root->right);
}
void postorder(treeNode* root)
{
if(root==NULL)
{
return;
}
postorder(root->left);
postorder(root->right);
cout<<root->data <<" ";
}
int main()
{
treeNode* root = takeinput();
printTree(root);
cout<<"Preorder traversal is: ";
preorder(root);
cout<<endl;
cout<<"Posteorder traversal is: ";
postorder(root);
cout<<endl;
cout<<"Intorder traversal is: ";
inorder(root);
delete(root);
return 0;
}