-
Notifications
You must be signed in to change notification settings - Fork 0
/
BoundaryOfBinaryTree.cpp
84 lines (83 loc) · 2.12 KB
/
BoundaryOfBinaryTree.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
/**
* 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 isLeaf(TreeNode * root){
return root && !root->left && !root->right;
}
void getLeaves(TreeNode * root, vector<TreeNode *>& leaves){
if(root == NULL){
return;
}
if(isLeaf(root)){
leaves.push_back(root);
}
getLeaves(root->left, leaves);
getLeaves(root->right, leaves);
}
vector<int> boundaryOfBinaryTree(TreeNode* root) {
if(root== NULL){
return {};
}
TreeNode * curr = NULL;
vector<TreeNode *> left;
if(root->left){
curr = root;
while(curr){
left.push_back(curr);
if(curr->left){
curr = curr->left;
}else{
curr = curr->right;
}
}
}else{
left.push_back(root);
}
vector<TreeNode *> leaves;
getLeaves(root, leaves);
vector<TreeNode *> right;
curr = root;
if(curr->right){
while(curr){
right.push_back(curr);
if(curr->right== NULL){
curr = curr->left;
}else{
curr = curr->right;
}
}
}else{
right.push_back(curr);
}
unordered_set<TreeNode *> s;
vector<int> res;
for(auto x: left){
if(s.find(x) == s.end()){
res.push_back(x->val);
s.insert(x);
}
}
for(auto x: leaves){
if(s.find(x) == s.end()){
res.push_back(x->val);
s.insert(x);
}
}
reverse(right.begin()+1, right.end());
for(auto x : right){
if(s.find(x) == s.end()){
res.push_back(x->val);
s.insert(x);
}
}
return res;
}
};