-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2. Boundary Traversal.cpp
92 lines (84 loc) · 1.69 KB
/
2. Boundary Traversal.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
// https://takeuforward.org/data-structure/boundary-traversal-of-a-binary-tree/
/*
Logic : Read above aritcal
Sperate traversal for left, bottam and right boundary.
!!!!!!! Some IMPORTANT : left_node and right_node function dont push root node, root node is pushed at the begining if it is not going to pushed by bottom function
*/
bool leaf(Node *root)
{
if (root->left == NULL && root->right == NULL)
{
return 1;
}
return 0;
}
void left_node(Node *root, vector<int> &ans)
{
Node *curr = root->left;
while (curr)
{
if (leaf(curr))
return;
ans.push_back(curr->data);
if (curr->left)
{
curr = curr->left;
}
else
{
curr = curr->right;
}
}
}
void right_node(Node *root, vector<int> &ans)
{
Node *curr = root->right;
vector<int> temp;
while (curr)
{
if (leaf(curr))
break;
temp.push_back(curr->data);
if (curr->right)
{
curr = curr->right;
}
else
{
curr = curr->left;
}
}
for (int i = temp.size() - 1; i >= 0; i--)
{
ans.push_back(temp[i]);
}
}
void bottom(Node *root, vector<int> &ans)
{
if (leaf(root))
{
ans.push_back(root->data);
}
if (root->left)
{
bottom(root->left, ans);
}
if (root->right)
{
bottom(root->right, ans);
}
}
vector<int> boundary(Node *root)
{
vector<int> ans;
if (root == NULL)
return ans;
if (!leaf(root))
{
ans.push_back(root->data);
}
left_node(root, ans);
bottom(root, ans);
right_node(root, ans);
return ans;
}