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 email@example.com. 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)
- Flatten Binary Tree in order of Level Order Traversal
- Insertion in n-ary tree in given order and Level order traversal
- Construct BST from its given level order traversal | Set-2
- Level Order Tree Traversal
- Construct BST from its given level order traversal
- Reverse Level Order Traversal
- Level order traversal in spiral form
- Level order traversal in spiral form | Using Deque
- Reverse Level Order traversal in spiral form
- Level order traversal with direction change after every two levels
- Zig Zag Level order traversal of a tree using single queue
- Check if two trees are mirror of each other using level order traversal
Improved By : Rajput-Ji