Boundary of Binary Tree

MediumSortingLinked ListTreeBinary TreeGraph

Description

Given a binary tree root, return the values of the boundary in anti-clockwise direction: left boundary, leaves, and right boundary.

Examples

Input:root = [1,null,2,3,4]
Output:[1,3,4,2]
Explanation:

Boundary traversal combines three separate traversals: the left boundary (nodes going down the left edge excluding leaves), all leaf nodes from left to right, and the right boundary in reverse order (nodes going up the right edge excluding leaves). This anti-clockwise approach ensures each boundary node appears exactly once in the correct order.

Input:root = [1,2,3,4,5,6,7]
Output:[1,2,4,5,6,7,3]
Explanation:

For a complete binary tree, traversing: root (1) → left boundary excluding leaves (2) → leaves from left to right (4,5,6,7) → right boundary excluding leaves in reverse (3). The anti-clockwise traversal gives us the outer boundary of the tree.

Input:root = [5,3,8,1,null,7,9,null,2]
Output:[5,3,1,2,7,9,8]
Explanation:

Starting from root (5), going down the left boundary (3,1), then collect leaves from left to right (2,7,9), and finally traverse up the right boundary in reverse (8). This creates an anti-clockwise boundary traversal around the tree's perimeter.

Constraints

  • 1 ≤ nodes ≤ 10⁴

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!