Understanding the Problem
In this problem, we are given a binary tree, and we need to return its boundary traversal in an anti-clockwise direction. The boundary traversal includes three parts:
- Left boundary: All the nodes from the root to the left-most node, excluding leaf nodes.
- Leaf nodes: All the leaf nodes from left to right.
- Right boundary: All the nodes from the right-most node to the root, excluding leaf nodes, and in reverse order.
To solve this, we must carefully avoid duplicates (especially leaf nodes appearing in both boundaries), and ensure we handle different tree shapes correctly.
Step-by-Step Solution with Example
Step 1: Choose an Example
1
/ 2 3
/ 4 5 6
/ 7 8
In this binary tree:
- Left Boundary: 1 → 2 (exclude 4 and 5 as they are leaf or part of leaf path)
- Leaves: 4, 7, 8, 6 (from left to right)
- Right Boundary: 3 (reverse order, exclude 6 as it's a leaf)
Expected Boundary Traversal: [1, 2, 4, 7, 8, 6, 3]
Step 2: Add Root
Always include the root first, unless it's the only node (handled as edge case). So, add 1
.
Step 3: Traverse Left Boundary
Starting from root.left
(i.e., 2), go down keeping only non-leaf nodes: add 2
.
Step 4: Collect Leaf Nodes
Do a full traversal and collect all nodes with no left or right child:
4, 7, 8, 6
Step 5: Traverse Right Boundary
Start from root.right
(i.e., 3) and collect non-leaf nodes in bottom-up order: [3]
Step 6: Combine All Parts
Merge: [1] + [2] + [4, 7, 8, 6] + [3] = [1, 2, 4, 7, 8, 6, 3]
Edge Cases
Case 1: Empty Tree
If the tree is empty (root == null
), return []
Case 2: Tree with Only Root Node
When there's only one node, it is both root and leaf. Output is [root]
Case 3: Left Skewed Tree
All nodes are part of the left boundary or leaves. Example:
1
/
2
/
3
Boundary traversal: [1, 2, 3]
Case 4: Right Skewed Tree
No left boundary. Only root, leaves, and right boundary exist:
1
2
3
Boundary traversal: [1, 3, 2]
Case 5: Tree with Only Left and Right Leaf
1
/ 2 3
Boundary traversal: [1, 2, 3]
(2 and 3 are leaves)
Finally
Boundary traversal of a binary tree is not just about walking around the edges — it's about understanding the structure and breaking it into meaningful parts: left boundary, leaves, and right boundary. Be careful not to include duplicates and ensure you handle edge cases like skewed or empty trees. A good approach always starts with understanding the structure and step-by-step traversal with clear rules.
Comments
Loading comments...