forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path545.Boundary of Binary Tree.cpp
85 lines (72 loc) · 2.05 KB
/
545.Boundary of Binary Tree.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
/**
* 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:
vector<int> boundaryOfBinaryTree(TreeNode* root)
{
vector<int>results;
if (root==NULL) return results;
results.push_back(root->val);
vector<int>Left;
if (root->left!=NULL)
{
GoLeft(root->left,Left);
Left.pop_back();
}
vector<int>Bottom;
if (root->left!=NULL || root->right!=NULL)
GoBottom(root,Bottom);
vector<int>Right;
if (root->right!=NULL)
{
GoRight(root->right,Right);
Right.pop_back();
}
reverse(Right.begin(),Right.end());
for (int i=0; i<Left.size(); i++)
results.push_back(Left[i]);
for (int i=0; i<Bottom.size(); i++)
results.push_back(Bottom[i]);
for (int i=0; i<Right.size(); i++)
results.push_back(Right[i]);
return results;
}
void GoLeft(TreeNode* root, vector<int>& Left)
{
if (root==NULL) return;
Left.push_back(root->val);
if (root->left!=NULL)
GoLeft(root->left,Left);
else if (root->right!=NULL)
GoLeft(root->right,Left);
}
void GoRight(TreeNode* root, vector<int>& Right)
{
if (root==NULL) return;
Right.push_back(root->val);
if (root->right!=NULL)
GoRight(root->right,Right);
else if (root->left!=NULL)
GoRight(root->left,Right);
}
void GoBottom(TreeNode* root, vector<int>& Bottom)
{
if (root==NULL) return;
if (root->left==NULL && root->right==NULL)
{
Bottom.push_back(root->val);
}
else
{
GoBottom(root->left,Bottom);
GoBottom(root->right,Bottom);
}
}
};