Boundary of Binary Tree

medium

Given the root of a binary tree, return the values of its boundary in anti-clockwise order, starting from the root.

The boundary is the concatenation of: the root; the left boundary (top-down, excluding leaves); the leaves (left to right); and the right boundary (bottom-up, excluding leaves). The left boundary is the path from the root's left child taking left when possible else right; the right boundary is symmetric. Each node appears once, and if the root is a leaf the boundary is just the root.

The tree is given in level-order (breadth-first), using null for missing children.

Hints

Assemble four parts: root, left boundary (top-down), leaves (left to right), right boundary (bottom-up).
Exclude leaves from the two side boundaries so they aren't counted twice.
Collect the right boundary top-down and reverse it, or append it post-order in recursion.

Common doubts

Skip leaves in the left and right boundary walks; the leaf pass covers them exactly once.
The anti-clockwise loop goes up the right side, but you naturally collect it top-down, so it must be reversed (or appended post-order).
The root is a leaf, so the boundary is just [root.val] — handle this before the side passes.

Interview follow-ups

It follows the right child instead, so the 'leftmost path' bends right when it must, keeping the boundary connected.
Reverse the roles: right boundary top-down, leaves right-to-left, left boundary bottom-up.

Fun facts

  • The recursive version gets bottom-up order for the right boundary for free by appending after the recursive call.
  • Boundary traversal is a favorite for testing careful handling of the leaf/edge overlap.

Asked at

AmazonMicrosoftGoogle
Frequently Sometimes Occasionally
Example 1
Input: root = [1, null, 2, 3, 4]
Output: [1, 3, 4, 2]
Root 1; no non-leaf left boundary; leaves 3, 4; right boundary (2) bottom-up.
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]
Root; left boundary 2; leaves 4, 7, 8, 9, 10; right boundary 6, 3 bottom-up.
Constraints

- The number of nodes is in the range [1, 10^4] - -1000 <= Node.val <= 1000

Solve this problem →