-
Notifications
You must be signed in to change notification settings - Fork 0
/
Boundary Traversal.cpp
85 lines (63 loc) · 2.15 KB
/
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
#include <bits/stdc++.h>
using namespace std;
/************************************************************
Following is the TreeNode class structure
template <typename T>
class TreeNode {
public:
T val;
TreeNode<T> *left;
TreeNode<T> *right;
TreeNode(T val) {
this->val = val;
left = NULL;
right = NULL;
}
};
************************************************************/
void traverseLeft(TreeNode<int>* root, vector<int> &ans) {
if(root == NULL || (root->left == NULL && root->right == NULL))
return;
ans.push_back(root->val);
if(root->left)
traverseLeft(root->left, ans);
else
traverseLeft(root->right, ans);
}
void traverseLeaf(TreeNode<int>* root, vector<int> &ans) {
if(root == NULL)
return;
if(root->left == NULL && root->right == NULL) {
ans.push_back(root->val);
return;
}
traverseLeaf(root->left, ans);
traverseLeaf(root->right, ans);
}
void traverseRight(TreeNode<int>* root, vector<int> &ans) {
if(root == NULL || (root->left == NULL && root->right == NULL))
return;
if(root->right)
traverseRight(root->right, ans);
else
traverseRight(root->left, ans);
ans.push_back(root->val); // Push while backtracking
}
vector<int> boundaryTraversal(TreeNode<int> *root) {
vector<int> ans;
if(root == NULL)
return ans;
// Add root node value
ans.push_back(root->val);
// Traverse the left boundary (excluding leaf nodes)
traverseLeft(root->left, ans);
// Traverse all the leaf nodes (left subtree first, then right subtree)
traverseLeaf(root->left, ans);
traverseLeaf(root->right, ans);
// Traverse the right boundary (excluding leaf nodes), add in reverse
vector<int> rightBoundary;
traverseRight(root->right, rightBoundary);
// Append the right boundary to the result in reverse order
ans.insert(ans.end(), rightBoundary.begin(), rightBoundary.end());
return ans;
}