Given a perfect binary tree, print nodes of middle level without computing its height. A perfect binary tree is a binary tree in which all interior nodes have two children and all leaves have the same depth or same level.
Output : 4 5 6 7
The idea is similar to method 2 of finding middle of singly linked list.
Use fast and slow (or tortoise) pointers in each route of the tree.
- Advance fast pointer towards leaf by 2.
- Advance slow pointer towards lead by 1.
- If fast pointer reaches the leaf print value at the slow pointer
- Check if the fast->left->left exists, then recursively move slow pointer by one step and fast pointer by two steps.
- If the fast->left->left doesn’t exist (in case of even number of levels), the move both the pointers by one step.
This article is contributed by Balkishan. You could hit me an email – email@example.com 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.
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.
- Print the middle nodes of each level of a Binary Tree
- Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
- Print the nodes corresponding to the level value for each level of a Binary Tree
- Calculate height of Binary Tree using Inorder and Level Order Traversal
- Height of binary tree considering even level leaves only
- Perfect Binary Tree Specific Level Order Traversal
- Perfect Binary Tree Specific Level Order Traversal | Set 2
- Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree
- Difference between sums of odd level and even level nodes of a Binary Tree
- Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree
- Nodes at Kth level without duplicates in a Binary Tree
- Print the nodes of the Binary Tree whose height is a Prime number
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Difference between sums of odd level and even level nodes in an N-ary Tree
- Postorder traversal of Binary Tree without recursion and without stack
- Middle To Up-Down Order traversal of a Binary Tree
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Print nodes between two given level numbers of a binary tree
- Print extreme nodes of each level of Binary Tree in alternate order
- Print odd positioned nodes of odd levels in level order of the given binary tree