[LeetCode] Boundary of Binary Tree

545. Boundary of Binary Tree

The boundary of a binary tree is the concatenation of the root, the left boundary, the leaves ordered from left-to-right, and the reverse order of the right boundary.

The left boundary is the set of nodes defined by the following:

  • The root node’s left child is in the left boundary. If the root does not have a left child, then the left boundary is empty.
  • If a node in the left boundary and has a left child, then the left child is in the left boundary.
  • If a node is in the left boundary, has no left child, but has a right child, then the right child is in the left boundary.
  • The leftmost leaf is not in the left boundary.

The right boundary is similar to the left boundary, except it is the right side of the root’s right subtree. Again, the leaf is not part of the right boundary, and the right boundary is empty if the root does not have a right child.

The leaves are nodes that do not have any children. For this problem, the root is not a leaf.

Given the root of a binary tree, return the values of its boundary.

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
/**
* 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 {
vector<int> res;
void pushLeft(TreeNode* node) {
if(!node) return;
res.push_back(node->val);
if(node->left) {
pushLeft(node->left);
pushLeaf(node->right);
} else pushLeft(node->right);
}
void pushRight(TreeNode* node) {
if(!node) return;
if(node->right) {
pushLeaf(node->left);
pushRight(node->right);
} else pushRight(node->left);
res.push_back(node->val);
}
void pushLeaf(TreeNode* node) {
if(!node) return;
if(!node->right && !node->left) {
res.push_back(node->val);
} else {
pushLeaf(node->left);
pushLeaf(node->right);
}
}
public:
vector<int> boundaryOfBinaryTree(TreeNode* root) {
res.push_back(root->val);
pushLeft(root->left);
pushRight(root->right);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/29/PS/LeetCode/boundary-of-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.