Given a complete binary tree, traverse it such that all the boundary nodes are visited in Anti-Clockwise order starting from the root.
Input: 18 / \ 15 30 / \ / \ 40 50 100 20 Output: 18 15 40 50 100 20 30
- Traverse left-most nodes of the tree from top to down. (Left boundary)
- Traverse bottom-most level of the tree from left to right. (Leaf nodes)
- Traverse right-most nodes of the tree from bottom to up. (Right boundary)
We can traverse the left boundary quite easily with the help of a while loop that checks when the node doesn’t have any left child. Similarly, we can traverse the right boundary quite easily with the help of a while loop that checks when the node doesn’t have any right child.
The main challenge here is to traverse the last level of the tree in left to right order. To traverse level-wise there is BFS and order of left to right can be taken care of by pushing left nodes in the queue first. So the only thing left now is to make sure it is the last level. Just check whether the node has any child and only include them.
We will have to take special care of the corner case that same nodes are not traversed again. In the example above 40 is a part of the left boundary as well as leaf nodes. Similarly, 20 is a part of the right boundary as well as leaf nodes.
So we will have to traverse only till the second last node of both the boundaries in that case. Also keep in mind we should not traverse the root again.
Below is the implementation of the above approach:
20 8 4 25 10 14 22
- Boundary Traversal of binary tree
- Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution)
- Iterative diagonal traversal of binary tree
- Sum of all the Boundary Nodes of a Binary Tree
- Iterative Preorder Traversal of an N-ary Tree
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Linked complete binary tree & its creation
- Height of a complete binary tree (or Heap) with N nodes
- Find the largest Complete Subtree in a given Binary Tree
- Iterative Search for a key 'x' in Binary Tree
- Number of edges in mirror image of Complete binary tree
- Sum of the mirror image nodes of a complete binary tree in an inorder way
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.