-
Notifications
You must be signed in to change notification settings - Fork 0
/
binaryTreeTraversal.cpp
113 lines (96 loc) · 2.31 KB
/
binaryTreeTraversal.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
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class node
{
public:
node(int val);
~node();
int nodeVal;
node* left;
node* right;
};
node::node(int val): nodeVal(val), left(nullptr), right(nullptr)
{
//nodeVal = val;
//left = nullptr;
//right = nullptr;
}
node::~node()
{
cout << "calling destructor for node "<< nodeVal << endl;
}
// self, left, right
void preOrderTran(node* root, vector<int>& result)
{
if (!root)
return;
cout << root->nodeVal << endl;
result.push_back(root->nodeVal);
preOrderTran(root->left, result);
preOrderTran(root->right, result);
}
// left, self, right
void inOrderTran(node* root, vector<int>& result)
{
if (!root)
return;
inOrderTran(root->left, result);
cout << root->nodeVal << endl;
result.push_back(root->nodeVal);
inOrderTran(root->right, result);
}
// left, right, self
void postOrderTran(node* root, vector<int>& result)
{
// base case
if (!root)
return;
postOrderTran(root->left, result);
postOrderTran(root->right, result);
cout << root->nodeVal << endl;
result.push_back(root->nodeVal);
}
int getHeight(node* root)
{
if (!root)
return 0;
int leftChildHeight = getHeight(root->left);
int rightChildHeight = getHeight(root->right);
return 1 + std::max(leftChildHeight, rightChildHeight);
}
int main ()
{
// 10
// 5 15
//2 7 12 20
node* root = new node(10);
root->left = new node(5);
root->right = new node(15);
root->left->left = new node(2);
root->left->right = new node(7);
root->right->left = new node(12);
root->right->right = new node(20);
vector<int> result;
//preOrderTran(root, result);
//inOrderTran(root, result);
postOrderTran(root, result);
//for (auto x:result)
// cout << x << endl;
cout << "tree height is " << getHeight(root) << endl;
// level order traversal
std::queue<node*> que;
que.push(root);
while (!que.empty())
{
node* cur = que.front();
que.pop();
cout << cur->nodeVal << endl;
if (cur->left)
que.push(cur->left);
if (cur->right)
que.push(cur->right);
}
return 0;
}