Create Balanced Binary Tree using its Leaf Nodes without using extra space
Output: 7 8 5 9 10 Explanation: Required balanced binary tree will be:
Output: 13 21 29 7 15 Explanation: Required balanced binary tree is: 29 / \ 21 7 / \ 13 15
Follow the steps below to solve the problem:
- Find all the leaf nodes in the given binary tree and create a doubly linked list using them.
- To create a Balanced Binary Tree from the above doubly linked list do the following:
- Find the middle node of the doubly linked list formed above and set it as a root node of the resultant tree.
- Recursively iterate for the left and right of the current middle node in the doubly linked list repeat the above steps until all nodes are covered.
- Print the newly created balanced binary tree.
Below is the implementation of the above approach:
7 8 5 9 10
Time Complexity: O(N), where N is the number of nodes in the given tree.
Auxiliary Space Complexity: O(1)
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.