Given a binary tree, print boundary nodes of the binary tree Anti-Clockwise starting from the root. The boundary includes left boundary, leaves, and right boundary in order without duplicate nodes. (The values of the nodes may still be duplicates.)
The left boundary is defined as the path from the root to the left-most node. The right boundary is defined as the path from the root to the right-most node. If the root doesn’t have left subtree or right subtree, then the root itself is left boundary or right boundary. Note this definition only applies to the input binary tree, and not apply to any subtrees.
The left-most node is defined as a leaf node you could reach when you always firstly travel to the left subtree if it exists. If not, travel to the right subtree. Repeat until you reach a leaf node.
The right-most node is also defined in the same way with left and right exchanged.
For example, boundary traversal of the following tree is “20 8 4 10 14 25 22”
We break the problem in 3 parts:
1. Print the left boundary in top-down manner.
2. Print all leaf nodes from left to right, which can again be sub-divided into two sub-parts:
…..2.1 Print all leaf nodes of left sub-tree from left to right.
…..2.2 Print all leaf nodes of right subtree from left to right.
3. Print the right boundary in bottom-up manner.
We need to take care of one thing that nodes are not printed again. e.g. The left most node is also the leaf node of the tree.
Based on the above cases, below is the implementation:
20 8 4 10 14 25 22
Time Complexity: O(n) where n is the number of nodes in binary tree.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Iterative Boundary Traversal of Complete Binary tree
- Boundary Level order traversal of a Binary Tree
- Boundary Root to Leaf Path traversal of a Binary Tree
- Sum of all the Boundary Nodes of a Binary Tree
- Level order traversal of Binary Tree using Morris Traversal
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Density of Binary Tree in One Traversal
- Diagonal Traversal of Binary Tree
- Mix Order Traversal of a Binary Tree
- Zig-Zag traversal of a Binary Tree using Recursion
- Reverse zigzag Traversal of a Binary Tree
- Double Order Traversal of a Binary Tree
- Left-Right traversal of all the levels of Binary tree
- Triple Order Traversal of a Binary Tree
- Clockwise Triangular traversal of a Binary Tree
- Iterative diagonal traversal of binary tree
- Clockwise Spiral Traversal of Binary Tree | Set - 2
- Middle To Up-Down Order traversal of a Binary Tree