-
Notifications
You must be signed in to change notification settings - Fork 0
/
boundaryTraversal.cpp
105 lines (102 loc) · 2.46 KB
/
boundaryTraversal.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
// Implemented by Kritagya Kumra
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class node
{
public:
int data;
node *left;
node *right;
node(int d)
{
this->data = d;
this->left = NULL;
this->right = NULL;
}
};
void traverseLeft(node *root, vector<int> &ans)
{
if ((root == NULL) || (root->left == NULL && root->right == NULL))
{
return;
}
ans.push_back(root->data);
if (root->left != NULL)
traverseLeft(root->left, ans);
else
traverseLeft(root->right, ans);
}
void traverseLeaf(node *root, vector<int> &ans)
{
if (root == NULL)
{
return;
}
if (root->left == NULL && root->right == NULL)
{
ans.push_back(root->data);
return;
}
if (root->left != NULL)
traverseLeaf(root->left, ans);
if (root->right != NULL)
traverseLeaf(root->right, ans);
}
void traverseRight(node *root, vector<int> &ans)
{
if ((root == NULL) || (root->left == NULL && root->right == NULL))
{
return;
}
if (root->right != NULL)
traverseRight(root->right, ans);
else
traverseRight(root->left, ans);
ans.push_back(root->data);
}
vector<int> boundaryTraversal(node *root)
{
vector<int> ans;
if (root == NULL)
{
return ans;
}
ans.push_back(root->data);
traverseLeft(root->left, ans);
traverseLeaf(root->left, ans);
traverseLeaf(root->right, ans);
traverseRight(root->right, ans);
return ans;
}
int main()
{
node *root1 = new node(10);
root1->left = new node(8);
root1->right = new node(2);
root1->left->left = new node(3);
root1->left->right = new node(5);
root1->right->left = new node(22);
root1->right->left->right = new node(12);
root1->right->left->right->left = new node(11);
// node *root1 = new node(20);
// root1->left = new node(8);
// root1->right = new node(12);
// root1->left->left = new node(3);
// root1->left->right = new node(5);
// root1->right->left = new node(2);
// root1->right->right = new node(10);
node *root = new node(10);
root->left = new node(20);
root->right = new node(30);
root->left->left = new node(40);
root->left->right = new node(60);
// bool ans = isBalanced(root);
vector<int> ans = boundaryTraversal(root1);
for (int i = 0; i < ans.size(); i++)
{
cout << ans[i] << " ";
}
}
// Implemented by Kritagya Kumra