Tree Boundary Traversal - Problem
Given a binary tree, print the boundary nodes in anti-clockwise order. The boundary traversal consists of three parts:
1. Left boundary: All nodes on the path from root to the leftmost leaf (excluding the leaf)
2. Leaves: All leaf nodes from left to right
3. Right boundary: All nodes on the path from the rightmost leaf to root (excluding the leaf and root), printed in reverse order
Note: If the root is a leaf node, only print the root. The root should not be printed twice.
Input & Output
Example 1 — Complete Binary Tree
$
Input:
root = [1,2,3,4,5,6]
›
Output:
[1,2,4,5,6,3]
💡 Note:
Anti-clockwise boundary: root(1) → left boundary(2) → leaves(4,5,6) → right boundary(3) in reverse
Example 2 — Single Node
$
Input:
root = [1]
›
Output:
[1]
💡 Note:
Single node tree: root is the only boundary node
Example 3 — Left Skewed Tree
$
Input:
root = [1,2,null,3,null,4]
›
Output:
[1,2,3,4]
💡 Note:
Left boundary: 1→2→3, leaf: 4, no right boundary (all nodes are on left boundary)
Constraints
- 1 ≤ Number of nodes ≤ 104
- -1000 ≤ Node.val ≤ 1000
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code