-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTree.cpp
More file actions
112 lines (104 loc) · 1.9 KB
/
BinaryTree.cpp
File metadata and controls
112 lines (104 loc) · 1.9 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
106
107
108
109
110
111
112
#include<bits/stdc++.h>
#include<vector>
#include<queue>
#include<algorithm>
#include<stack>
#include<map>
#include<iostream>
using namespace std;
class TreeNode {
public:
int data;
TreeNode *left;
TreeNode *right;
TreeNode() {
data = 0;
left = NULL;
right = NULL;
}
TreeNode(int data) {
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
TreeNode* create() {
/*TreeNode *root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);*/
cout << "Enter data" << endl;
int data;
cin >> data;
if(data == -1) {
return NULL;
}
TreeNode *root = new TreeNode(data);
root->left = create();
root->right = create();
return root;
}
void preorder(TreeNode* root) { // root left right
if(root == NULL) {
return;
}
cout << root->data << " ";
preorder(root->left);
preorder(root->right);
return;
}
void inorder(TreeNode *root) { // left root right
if(root == NULL) {
return;
}
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
return;
}
void postorder(TreeNode *root) { // left right root
if(root == NULL) {
return;
}
postorder(root->left);
postorder(root->right);
cout << root->data << " ";
return;
}
void levelOrder(TreeNode* root) {
if(root == NULL) {
return;
}
queue<TreeNode*> q;
q.push(root);
while(q.empty() != true) {
int size = q.size();
for(int i=0; i<size; i++) {
TreeNode *temp = q.front();
q.pop();
cout << temp->data << " ";
if(temp->left != NULL) {
q.push(temp->left);
}
if(temp->right != NULL) {
q.push(temp->right);
}
}
cout << endl;
}
}
int main() {
TreeNode *root = create();
preorder(root);
cout << endl;
inorder(root);
cout << endl;
postorder(root);
cout << endl;
levelOrder(root);
cout << endl;
return 0;
}