Boundary of Binary Tree
Medium
Topics
The boundary of a binary tree is the concatenation of the root, the left boundary, the leaves ordered left to right, and the reversed right boundary.
The left boundary is built as follows. The root’s left child is on it; if the root has no left child, the left boundary is empty. From a node on the left boundary, its left child is next, or its right child if it has no left child. Leaves are never on the left boundary.
The right boundary is the mirror image: the root’s right child, then preferring right children over left, and again excluding leaves.
If the root is itself a leaf, the boundary is just the root.
Example 1
[1,3,4,2].null marks a missing child.Input: root = [1,null,2,3,4] Output: [1,3,4,2] Explanation: The root has no left child, so the left boundary is empty. The leaves are 3 and 4. The right boundary is just 2, since 4 is a leaf and excluded.
Example 2
Input: root = [1,2,3,4,5,6,null,null,null,7,8,9,10] Output: [1,2,4,7,8,9,10,6,3] Explanation: Left boundary 2 (4 is a leaf). Leaves 4, 7, 8, 9, 10. Right boundary 3 then 6, reversed to 6, 3.
Example 3
Input: root = [1] Output: [1] Explanation: The root is a leaf, so it alone forms the boundary.
Constraints
- 1 <= number of nodes <= 10^4
- -1000 <= Node.val <= 1000
Editorial — intuition, approach, complexity and pitfalls
Intuition
This is three separate walks glued together, and the only real difficulty is the overlap. A node can belong to more than one of the three categories — the leftmost leaf is both the end of the left boundary and the first leaf — so the rules deliberately exclude leaves from the two boundaries to make each node appear exactly once.
The root is also a special case for the same reason. It would qualify as the start of both boundaries, so it is handled once up front and the two boundary walks start from its children.
And a root with no children is a leaf, which would otherwise be emitted twice: once as the root and once as a leaf. Returning early on that tree removes the clash.
Approach
- Emit the root’s value. If the root has no children, stop — that is the whole boundary.
- Walk the left boundary from the root’s left child: emit the node, then move to its left child, or its right child if there is no left. Stop on reaching a leaf without emitting it.
- Walk the whole tree and emit every leaf in left-to-right order.
- Walk the right boundary from the root’s right child by the mirror rule, collecting nodes rather than emitting them, then append them reversed.
Walkthrough
root = [1,2,3,4,5,6,null,null,null,7,8,9,10]
1
/ \
2 3
/ \ /
4 5 6
/ \ / \
7 8 9 10
root -> 1
left boundary -> 2 (next would be 4, a leaf, so it stops)
leaves -> 4 7 8 9 10
right boundary -> 3, 6 (next would be 10, a leaf)
reversed -> 6, 3
answer [1,2,4,7,8,9,10,6,3]Complexity
- Time — O(n): the two boundary walks are each at most one root-to-leaf path, and the leaf collection visits every node once.
- Space — O(n): the output, plus recursion depth bounded by the tree height.
Common Pitfalls
- Not special-casing a root with no children. It gets emitted as the root and again as a leaf, so the answer comes back as two copies of one value.
- Including leaves in the boundary walks. The leftmost leaf then appears twice, once from the left walk and once from the leaf collection.
- Taking only left children down the left boundary. The rule falls back to the right child when there is no left one, so a tree that zig-zags still has a left boundary — stopping early truncates it.
- Forgetting to reverse the right boundary. The boundary is traced anticlockwise, so the right side is read bottom-up.
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def boundaryOfBinaryTree(self, root):
def is_leaf(n):
return n is not None and n.left is None and n.right is None
if not root:
return []
if is_leaf(root):
return [root.val]
out = [root.val]
node = root.left
while node and not is_leaf(node):
out.append(node.val)
node = node.left or node.right
def leaves(n):
if not n:
return
if is_leaf(n):
out.append(n.val)
return
leaves(n.left)
leaves(n.right)
leaves(root)
right = []
node = root.right
while node and not is_leaf(node):
right.append(node.val)
node = node.right or node.left
out.extend(reversed(right))
return outimport java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int[] boundaryOfBinaryTree(TreeNode root) {
List<Integer> out = new ArrayList<>();
if (root == null) return new int[]{};
if (isLeaf(root)) return new int[]{root.val};
out.add(root.val);
TreeNode node = root.left;
while (node != null && !isLeaf(node)) {
out.add(node.val);
node = node.left != null ? node.left : node.right;
}
leaves(root, out);
List<Integer> right = new ArrayList<>();
node = root.right;
while (node != null && !isLeaf(node)) {
right.add(node.val);
node = node.right != null ? node.right : node.left;
}
Collections.reverse(right);
out.addAll(right);
int[] res = new int[out.size()];
for (int i = 0; i < res.length; i++) res[i] = out.get(i);
return res;
}
private boolean isLeaf(TreeNode n) {
return n != null && n.left == null && n.right == null;
}
private void leaves(TreeNode n, List<Integer> out) {
if (n == null) return;
if (isLeaf(n)) {
out.add(n.val);
return;
}
leaves(n.left, out);
leaves(n.right, out);
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: vector<int> boundaryOfBinaryTree(TreeNode* root) {
auto isLeaf = [](TreeNode* n) {
return n && !n->left && !n->right;
};
vector<int> out;
if (!root) return out;
if (isLeaf(root)) {
out.push_back(root->val);
return out;
}
out.push_back(root->val);
TreeNode* node = root->left;
while (node && !isLeaf(node)) {
out.push_back(node->val);
node = node->left ? node->left : node->right;
}
function<void(TreeNode*)> leaves = [&](TreeNode* n) {
if (!n) return;
if (isLeaf(n)) {
out.push_back(n->val);
return;
}
leaves(n->left);
leaves(n->right);
};
leaves(root);
vector<int> right;
node = root->right;
while (node && !isLeaf(node)) {
right.push_back(node->val);
node = node->right ? node->right : node->left;
}
reverse(right.begin(), right.end());
for (int v : right) out.push_back(v);
return out;
}
};/**
* Tree node shape: { val, left, right }
* @param {TreeNode} root
* @return {number[]}
*/ var boundaryOfBinaryTree = function(root) {
const isLeaf = (n) => !!n && !n.left && !n.right;
if (!root) return [];
if (isLeaf(root)) return [root.val];
const out = [root.val];
let node = root.left;
while (node && !isLeaf(node)) {
out.push(node.val);
node = node.left || node.right;
}
const leaves = (n) => {
if (!n) return;
if (isLeaf(n)) {
out.push(n.val);
return;
}
leaves(n.left);
leaves(n.right);
};
leaves(root);
const right = [];
node = root.right;
while (node && !isLeaf(node)) {
right.push(node.val);
node = node.right || node.left;
}
right.reverse();
return out.concat(right);
};