AlgoInsight

DSA problem

Boundary of Binary Tree

MediumTree Traversal - Post-OrderPattern: Tree Traversal - Post-Ordertop600AmazonMicrosoftGoogleBloomberg

The boundary of a binary tree is the concatenation of its left boundary, the leaves (left to right), and the reversed right boundary. The left boundary is the path from the root following the leftmost edges down to (but not including) any leaf; the right boundary is similarly the rightmost path. If a node is both the root and a leaf — a tree of size one — the answer is simply that node.

The challenge is partitioning the work cleanly into three sub-traversals so each node is reported at most once and in the right order. Three pieces:

  1. Left boundary (top-down, excluding leaves): Walk from root.left, always preferring node.left; if node.left is null fall through to node.right. Skip leaves.
  2. Leaves (depth-first, left-to-right): A standard preorder traversal that emits a node only when it has no children.
  3. Right boundary (bottom-up, excluding leaves): Same as the left boundary but mirrored — prefer node.right else node.left — collected then reversed so it reads from bottom up to the root.

The concatenation is root → left boundary → leaves → reversed right boundary. Subtle points: do not include leaves twice (the left/right boundary walks must skip leaves), and handle the degenerate case where the tree is just a root. The algorithm visits each node a constant number of times across the three traversals, so the total work is O(n) with O(h) recursion space.

Examples

Example 1
Input: root = [1,null,2,3,4]
Output: [1,3,4,2]
Explanation: Left boundary (excluding leaves): empty. Leaves left-to-right: 3, 4. Right boundary reversed (excluding leaves): 2. Concatenated with root in front: 1,3,4,2.
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: Root 1, left boundary (2, 4), leaves (7, 8, 9, 10), reversed right boundary (6, 3).
Example 3
Input: root = [1]
Output: [1]
Explanation: A single node is the entire boundary.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

treebinary-treedepth-first-searchboundary

Browse all DSA problems