πDay 7. Tree Boundary Traversal π§
The problem can be found at the following link: Problem Link
π‘ Problem Description:
Given a binary tree, the task is to return a list of nodes representing its boundary traversal in an anticlockwise direction, starting from the root. The boundary includes:
The left boundary (excluding the leaf nodes).
All the leaf nodes (both from left and right subtrees).
The right boundary (excluding the leaf nodes), added in reverse order.
π Example Walkthrough:
Example 1
Input:
root[] = [1, 2, 3, 4, 5, 6, 7, N, N, 8, 9, N, N, N, N]
Output:
[1, 2, 4, 8, 9, 6, 7, 3]
Explanation:
Example 2
Input:
root[] = [1, 2, N, 4, 9, 6, 5, N, 3, N, N, N, N 7, 8]
Output:
[1, 2, 4, 6, 5, 7, 8]
Explanation:
Example 3
Input:
root[] = [1, N, 2, N, 3, N, 4, N, N]
Output:
[1, 4, 3, 2]
Explanation:
Left boundary: [1] (as there is no left subtree)Leaf nodes: [4]Right boundary: [3, 2] (in reverse order)Final traversal: [1, 4, 3, 2]
Constraints
1 <= Number of Nodes <= $10^4$
1 <= Node Value <= $10^5$
π― My Approach:
The boundary traversal of a binary tree consists of three parts:
Left Boundary:
Traverse the leftmost nodes, excluding the leaf nodes.
Move left whenever possible; otherwise, move right.
Leaf Nodes:
Perform inorder traversal to collect leaf nodes.
Right Boundary:
Traverse the rightmost nodes, excluding the leaf nodes.
Move right whenever possible; otherwise, move left.
Store nodes in a stack to reverse them before adding to the final result.
π Time and Auxiliary Space Complexity
Time Complexity:
O(N)Each node is visited at most once, so the time complexity is O(N).Auxiliary Space Complexity:
O(H)(Height of the tree) The recursion stack space in a skewed tree can be O(N). In a balanced tree, it will be O(log N).
π Solution Code
Code (C++)
π² Alternative Approaches
2οΈβ£ Iterative Approach Using Queue (BFS)
Algorithm
Traverse the left boundary iteratively.
Collect leaf nodes via BFS.
Traverse the right boundary iteratively in reverse order.
3οΈβ£ Iterative DFS (Using Stack)
Algorithm
Use DFS traversal to visit nodes iteratively.
Push the left boundary.
Collect leaf nodes.
Push the right boundary in reverse.
π Comparison of Approaches
Recursive DFS
π’ O(N)
π‘ O(H)
Recursion
Simple & structured
Stack overflow for deep trees
Iterative BFS
π’ O(N)
π΄ O(W)
Queue-based
Avoids recursion depth issues
More memory for wide trees
Iterative DFS (Stack)
π’ O(N)
π‘ O(H)
Stack-based
Explicit traversal order
Extra space for stack
π Best Choice?
For balanced trees, the Recursive DFS method is best.
For deep trees, the Iterative BFS is preferable.
For explicit iterative control, the DFS with Stack is an option.
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated