Write a function to connect all the adjacent nodes at the same level in a binary tree.
Input Tree A / \ B C / \ \ D E F Output Tree A--->NULL / \ B-->C-->NULL / \ \ D-->E-->F-->NULL
We have already discussed O(n^2) time and O approach in Connect nodes at same level as morris traversal in worst case can be O(n) and calling it to set right pointer can result in O(n^2) time complexity.
In this post, We have discussed Level Order Traversal with NULL markers which are needed to mark levels in tree.
Following are populated nextRight pointers in the tree (-1 is printed if there is no nextRight) nextRight of 10 is -1 nextRight of 8 is 2 nextRight of 2 is -1 nextRight of 3 is 90 nextRight of 90 is -1
Time complexity :O(n) where n is the number of nodes
We can also follow the implementation discussed in Print level order traversal line by line | Set 1. We keep connecting nodes of same level by keeping track of prev visited node of same level.
Implementation : https://ide.geeksforgeeks.org/gV1Oc2
Thanks to Akilan Sengottaiyan for suggesting this alternate implementation.
This article is contributed by Abhishek Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Connect nodes at same level
- Connect nodes at same level using constant extra space
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Reverse Level Order Traversal
- Level Order Tree Traversal
- Construct BST from its given level order traversal
- Level order traversal in spiral form
- Zig Zag Level order traversal of a tree using single queue
- Check if two trees are mirror of each other using level order traversal
- Reverse Level Order traversal in spiral form
- Level order traversal with direction change after every two levels
- Density of Binary Tree using Level Order Traversal
- Difference between sums of odd level and even level nodes of a Binary Tree
- Level order traversal in spiral form | Using one stack and one queue
- Perfect Binary Tree Specific Level Order Traversal | Set 2
Improved By : Rajput-Ji