Problem
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 itsboundary.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
- The number of nodes in the tree is in the range
[1, 10^4]
. -1000 <= Node.val <= 1000
Solution
Method 1 – DFS for Left Boundary, Leaves, and Right Boundary
Intuition
The boundary of a binary tree can be constructed by traversing the left boundary, collecting all leaves, and then traversing the right boundary in reverse. We use DFS to collect each part, taking care to avoid duplicates.
Approach
- If the tree is empty, return an empty list.
- Add the root value to the answer.
- Traverse the left boundary (excluding leaves and root) using DFS.
- Traverse all leaves (excluding those already in the boundary) using DFS.
- Traverse the right boundary (excluding leaves and root) using DFS, and add them in reverse order.
- Return the concatenated result.
Code
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
— Each node is visited at most once. - 🧺 Space complexity:
O(h)
— h is the height of the tree (recursion stack).