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
INPUT TREE123456Binary tree withnodes [1,2,3,4,5,6]ALGORITHM1Identify BoundariesRoot: 1 (blue)Left boundary: 2 (red)Leaves: 4,5,6 (green)Right boundary: 3 (purple)2Traverse Anti-clockwiseStart from rootGo down left boundaryCollect leaves left to rightGo up right boundary (reverse)3Combine ResultsRoot + Left + Leaves + Right= [1] + [2] + [4,5,6] + [3]RESULTBoundary Array[1,2,4,5,6,3]Anti-clockwise traversalof boundary nodesOrder Maintained:Root → Left → Leaves → RightKey Insight:Tree boundary traversal follows a natural anti-clockwise path: start at root, go down leftboundary, collect leaves from left to right, then go up right boundary in reverse order.Single DFS with boundary flags achieves O(n) time and O(h) space complexity.TutorialsPoint - Tree Boundary Traversal | Single DFS Traversal
Asked in
Amazon 25 Microsoft 20 Google 15 Facebook 12
32.0K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen