π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++)
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