forked from jhflorey/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBoundary-of-binary-tree.cpp
executable file
·62 lines (60 loc) · 1.49 KB
/
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
/*
*
* Tag: DFS
* Time: O(n)
* Space: O(n)
*/
/**
* 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> ans;
if(root == NULL)
return ans;
ans.push_back(root->val);
lbnd(root->left, ans);
dfs(root->left, ans);
dfs(root->right, ans);
rbnd(root->right, ans);
return ans;
}
private:
void lbnd(TreeNode *root, vector<int> &ans){
if(root == NULL || (root->left == NULL && root->right == NULL))
return ;
ans.push_back(root->val);
if(root->left)
lbnd(root->left, ans);
else
lbnd(root->right, ans);
}
void rbnd(TreeNode *root, vector<int> &ans){
if(root == NULL || (root->left == NULL && root->right == NULL))
return ;
if(root->right)
rbnd(root->right, ans);
else
rbnd(root->left, ans);
ans.push_back(root->val);
}
void dfs(TreeNode *root, vector<int> &ans){
if(root == NULL)
return ;
if(root->left == NULL && root->right == NULL){
ans.push_back(root->val);
return ;
}
if(root->left)
dfs(root->left, ans);
if(root->right)
dfs(root->right, ans);
}
};