-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBoundaryBinaryTree.cpp
62 lines (62 loc) · 1.72 KB
/
BoundaryBinaryTree.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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool is_leaf(TreeNode* root)
{
return ((root->left == NULL) && (root->right == NULL));
}
void add_leaves(TreeNode* root, vector<int>& res)
{
if(root == NULL)
return;
if(is_leaf(root))
{
res.push_back(root->val);
return;
}
add_leaves(root->left,res);
add_leaves(root->right,res);
}
vector<int> boundaryOfBinaryTree(TreeNode* root) {
vector<int>res;
if(root==NULL)
return res;
res.push_back(root->val);
if(is_leaf(root))
return res;
TreeNode* left_boundary = root->left;
while((left_boundary!=NULL) && (!is_leaf(left_boundary)))
{
res.push_back(left_boundary->val);
if(left_boundary->left!=NULL)
left_boundary = left_boundary->left;
else if(left_boundary->right!=NULL)
left_boundary=left_boundary->right;
}
add_leaves(root,res);
stack<int>st;
TreeNode* right_boundary = root->right;
while((right_boundary!=NULL)&&(!is_leaf(right_boundary)))
{
st.push(right_boundary->val);
if(right_boundary->right!=NULL)
right_boundary=right_boundary->right;
else if(right_boundary->left!=NULL)
right_boundary = right_boundary->left;
}
while(!st.empty())
{
res.push_back(st.top());
st.pop();
}
return res;
}
};