-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.cpp
More file actions
69 lines (60 loc) · 2.23 KB
/
code.cpp
File metadata and controls
69 lines (60 loc) · 2.23 KB
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
// This is for the leetcode version of the problem
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void traverseLeftBoundary(TreeNode* root, vector<int>& boundary) {
if (root == nullptr || (root->left == nullptr && root->right == nullptr)) {
return;
}
boundary.push_back(root->val);
if (root->left != nullptr) {
traverseLeftBoundary(root->left, boundary);
}
else {
traverseLeftBoundary(root->right, boundary);
}
}
void traverseAndFindChildren(TreeNode* root, vector<int>& boundary) {
if (root == nullptr) {
return;
}
if (root->left == nullptr && root->right == nullptr) {
boundary.push_back(root->val);
}
traverseAndFindChildren(root->left, boundary);
traverseAndFindChildren(root->right, boundary);
}
void traverseRightBoundary(TreeNode* root, vector<int>& boundary) {
if (root == nullptr || (root->left == nullptr && root->right == nullptr)) {
return;
}
if (root->right != nullptr) {
traverseRightBoundary(root->right, boundary);
}
else {
traverseRightBoundary(root->left, boundary);
}
boundary.push_back(root->val);
}
vector<int> boundaryOfBinaryTree(TreeNode* root) {
vector<int> boundary;
if (root != nullptr) {
boundary.push_back(root->val);
}
traverseLeftBoundary(root->left, boundary);
traverseAndFindChildren(root->left, boundary);
traverseAndFindChildren(root->right, boundary);
traverseRightBoundary(root->right, boundary);
return boundary;
}
};