-
Notifications
You must be signed in to change notification settings - Fork 0
/
Boundary Traversal of Binary Tree CodignNinjas.cpp
59 lines (51 loc) · 1.24 KB
/
Boundary Traversal of Binary Tree CodignNinjas.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
// tc=o(n+n+n)
// sc=o(n+n)
#include <bits/stdc++.h>
using namespace std;
bool isLeaf(TreeNode<int>* root){
if(!root) return false;
if(!root->left && !root->right)
return true;
else
return false;
}
void left(TreeNode<int>* root, vector<int>& res){
TreeNode<int>* node=root->left;
while(node){
if(!isLeaf(node)) res.push_back(node->data);
if(node->left) node=node->left;
else node=node->right;
}
}
void leaves(TreeNode<int>* root, vector<int>& res){
if(!root) return;
if(isLeaf(root)){
res.push_back(root->data);
return;
}
leaves(root->left,res);
leaves(root->right,res);
}
void right(TreeNode<int>* root, vector<int>& res){
TreeNode<int>* node=root->right;
stack<int> stk;
while(node){
if(!isLeaf(node)) stk.push(node->data);
if(node->right) node=node->right;
else node=node->left;
}
while(!stk.empty()){
res.push_back(stk.top());
stk.pop();
}
}
vector<int> traverseBoundary(TreeNode<int>* root){
if(!root) return {};
if(isLeaf(root)) return {root->data};
vector<int> res;
res.push_back(root->data);
left(root,res);
leaves(root,res);
right(root,res);
return res;
}