← DiffPush

Boundary Traversal of Binary Tree

Standard Bar Binary Trees · Medium Problems O(n) · O(h)

The Perimeter Fence Patrol

A heritage orchard is pruned into a binary tree of plots, and the annual inspector walks only the perimeter: down the leftmost fence, across every dead-end plot left to right, then back up the rightmost fence toward the gate. Interior plots are skipped, and the root counts once no matter how many fences meet there. The patrol log is the official boundary record.

Input: The root of a binary tree given as a level-order array where null marks a missing child.

Output: Return an array: root, then left-boundary non-leaf nodes top-down, then all leaves left-to-right, then right-boundary non-leaf nodes bottom-up (root excluded).

Constraints

Examples

Example 1

Input: {"tree":[1,2,3,4,5,6,7,null,null,8,9]}
Output: [1,2,4,8,9,6,7,3]
Left fence 2, leaves 4,8,9,6,7 left to right, then the right fence climbs 3.

Example 2

Input: {"tree":[1]}
Output: [1]
A lone plot is its own boundary — listed exactly once.

Solve this in your browser →

Also on LeetCode ↗