Create Balanced Binary Tree using its Leaf Nodes without using extra space

Prerequisites: Binary Tree to Doubly Linked List
Given a Binary Tree, the task is to create a Balanced Binary Tree from all the leaf nodes of the given Binary Tree.
Examples:Â
Input:
Output: 7 8 5 9 10 Explanation: Required balanced binary tree will be:
Input:
Output: 13 21 29 7 15
Explanation: Required balanced binary tree is:
29
/ \
21 7
/ \
13 15
Approach:Â
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:Â Â
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Structure for Linked list and treeclass Node {public:Â Â Â Â int data;Â Â Â Â Node *left, *right;};Â
// Function that returns the count of// nodes in the given linked listint countNodes(Node* head){    // Initialize count    int count = 0;Â
    Node* temp = head;Â
    // Iterate till the end of LL    while (temp) {Â
        temp = temp->right;Â
        // Increment the count        count++;    }Â
    // Return the final count    return count;}Â
// Function to return the root of// the newly created balanced binary// tree from the given doubly LLNode* sortedListToBSTRecur(    Node** head_ref, int n){    // Base Case    if (n <= 0)        return NULL;Â
    // Recursively construct    // the left subtree    Node* left = sortedListToBSTRecur(        head_ref, n / 2);Â
    // head_ref now refers to    // middle node, make middle node    // as root of BST    Node* root = *head_ref;Â
    // Set pointer to left subtree    root->left = left;Â
    // Change head pointer of    // Linked List for parent    // recursive calls    *head_ref = (*head_ref)->right;Â
    // Recursively construct the    // right subtree and link it    // with root        root->right        = sortedListToBSTRecur(            head_ref, n - n / 2 - 1);Â
    // Return the root of Balanced BT    return root;}Node* sortedListToBST(Node* head){    /*Count the number of     nodes in Linked List */    int n = countNodes(head);Â
    /* Construct BST */    return sortedListToBSTRecur(        &head, n);}Â
// Function to find the leaf nodes and// make the doubly linked list of// those nodesNode* extractLeafList(Node* root,                      Node** head_ref){    // Base cases    if (root == NULL)        return NULL;Â
    if (root->left == NULL        && root->right == NULL) {Â
        // This node is added to doubly        // linked list of leaves, and        // set right pointer of this        // node as previous head of DLL        root->right = *head_ref;Â
        // Change left pointer        // of previous head        if (*head_ref != NULL)            (*head_ref)->left = root;Â
        // Change head of linked list        *head_ref = root;Â
        // Return new root        return NULL;    }Â
    // Recur for right & left subtrees    root->right = extractLeafList(root->right,                                  head_ref);    root->left = extractLeafList(root->left,                                 head_ref);Â
    // Return the root    return root;}Â
// Function to allocating new Node// int Binary TreeNode* newNode(int data){Â Â Â Â Node* node = new Node();Â Â Â Â node->data = data;Â Â Â Â node->left = NULL;Â Â Â Â node->right = NULL;Â Â Â Â return node;}Â
// Function for inorder traversalvoid print(Node* root){Â Â Â Â // If root is not NULLÂ Â Â Â if (root != NULL) {Â
        print(root->left);Â
        // Print the root's data        cout << root->data             << " ";        print(root->right);    }}Â
// Function to display nodes of DLLvoid printList(Node* head){Â Â Â Â while (head) {Â
        // Print the data        cout << head->data << " ";        head = head->right;    }}Â
// Driver Codeint main(){    // Given Binary Tree    Node* head = NULL;    Node* root = newNode(1);Â
    root->left = newNode(2);    root->right = newNode(3);    root->left->left = newNode(4);    root->left->right = newNode(5);    root->right->right = newNode(6);    root->left->left->left = newNode(7);    root->left->left->right = newNode(8);    root->right->right->left = newNode(9);    root->right->right->right = newNode(10);Â
    // Function Call to extract leaf Node    root = extractLeafList(        root, &head);Â
    // Function Call to create Balanced BT    root = sortedListToBST(head);Â
    // Print Inorder traversal New Balanced BT    print(root);    return 0;} |
Java
// Java program for // the above approachimport java.util.*;class GFG{Â
// Structure for Linked // list and treestatic class Node {  public int data;  Node left, right;};   static Node head;   // Function that returns the // count of nodes in the given // linked liststatic int countNodes(Node head){  // Initialize count  int count = 0;Â
  Node temp = head;Â
  // Iterate till the   // end of LL  while (temp != null)   {    temp = temp.right;Â
    // Increment the count    count++;  }Â
  // Return the final count  return count;}Â
// Function to return the root of// the newly created balanced binary// tree from the given doubly LLstatic Node sortedListToBSTRecur(int n){  // Base Case  if (n <= 0)    return null;Â
  // Recursively construct  // the left subtree  Node left = sortedListToBSTRecur(n / 2);Â
  // head now refers to  // middle node, make   // middle node as root of BST  Node root = head;Â
  // Set pointer to left subtree  root.left = left;Â
  // Change head pointer of  // Linked List for parent  // recursive calls  head = head.right;Â
  // Recursively construct the  // right subtree and link it  // with root  root.right = sortedListToBSTRecur(n - n /                                     2 - 1);Â
  // Return the root   // of Balanced BT  return root;}   static Node sortedListToBST(){  // Count the number of   // nodes in Linked List  int n = countNodes(head);Â
  // Construct BST  return sortedListToBSTRecur(n);}Â
// Function to find the leaf nodes and// make the doubly linked list of// those nodesstatic Node extractLeafList(Node root){  // Base cases  if (root == null)    return null;Â
  if (root.left == null &&       root.right == null)   {    // This node is added to doubly    // linked list of leaves, and    // set right pointer of this    // node as previous head of DLL    root.right = head;Â
    // Change left pointer    // of previous head    if (head != null)      head.left = root;Â
    // Change head of linked list    head = root;Â
    // Return new root    return head;  }Â
  // Recur for right &   // left subtrees  root.right =        extractLeafList(root.right);  root.left =        extractLeafList(root.left);Â
  // Return the root  return root;}Â
// Function to allocating new // Node int Binary Treestatic Node newNode(int data){Â Â Node node = new Node();Â Â node.data = data;Â Â node.left = null;Â Â node.right = null;Â Â return node;}Â
// Function for inorder traversalstatic void print(Node root){  // If root is not null  if (root != null)   {    print(root.left);Â
    // Print the root's data    System.out.print(root.data + " ");    print(root.right);  }}Â
// Function to display nodes of DLLstatic void printList(Node head){  while (head != null)   {    // Print the data    System.out.print(head.data + " ");    head = head.right;  }}Â
// Driver Codepublic static void main(String[] args){  // Given Binary Tree  head = null;  Node root = newNode(1);Â
  root.left = newNode(2);  root.right = newNode(3);  root.left.left = newNode(4);  root.left.right = newNode(5);  root.right.right = newNode(6);  root.left.left.left = newNode(7);  root.left.left.right = newNode(8);  root.right.right.left = newNode(9);  root.right.right.right = newNode(10);Â
  // Function Call to   // extract leaf Node  root = extractLeafList(root);Â
  // Function Call to create   // Balanced BT  root = sortedListToBST();Â
  // Print Inorder traversal   // New Balanced BT  print(root);}}Â
// This code is contributed by Amit Katiyar |
Python3
# Python3 program for the above approachÂ
# Structure for Linked list and treeclass newNode:         def __init__(self, data):                 self.data = data        self.left = None        self.right = NoneÂ
head = NoneÂ
# Function that returns the count of# nodes in the given linked listdef countNodes(head1):         # Initialize count    count = 0Â
    temp = head1Â
    # Iterate till the end of LL    while (temp):        temp = temp.rightÂ
        # Increment the count        count += 1Â
    # Return the final count    return countÂ
# Function to return the root of# the newly created balanced binary# tree from the given doubly LLdef sortedListToBSTRecur(n):         global head         # Base Case    if (n <= 0):        return NoneÂ
    # Recursively construct    # the left subtree    left = sortedListToBSTRecur(n // 2)Â
    # head_ref now refers to    # middle node, make middle node    # as root of BST    root = headÂ
    # Set pointer to left subtree    root.left = leftÂ
    # Change head pointer of    # Linked List for parent    # recursive calls    head = head.rightÂ
    # Recursively construct the    # right subtree and link it    # with root    root.right = sortedListToBSTRecur(n - n //                                      2 - 1)Â
    # Return the root of Balanced BT    return rootÂ
def sortedListToBST():         global head         # Count the number of nodes    # in Linked List     n = countNodes(head)Â
    # Construct BST     return sortedListToBSTRecur(n)Â
# Function to find the leaf nodes and# make the doubly linked list of# those nodesdef extractLeafList(root):         global head         # Base cases    if (root == None):        return NoneÂ
    if (root.left == None and       root.right == None):                 # This node is added to doubly        # linked list of leaves, and        # set right pointer of this        # node as previous head of DLL        root.right = headÂ
        # Change left pointer        # of previous head        if (head != None):            head.left = rootÂ
        # Change head of linked list        head = rootÂ
        # Return new root        return headÂ
    # Recur for right & left subtrees    root.right = extractLeafList(root.right)    root.left = extractLeafList(root.left)Â
    # Return the root    return rootÂ
# Function for inorder traversaldef print1(root):Â Â Â Â Â Â Â Â Â # If root is not NULLÂ Â Â Â if (root != None):Â Â Â Â Â Â Â Â print1(root.left)Â
        # Print the root's data        print(root.data, end = " ")        print1(root.right)Â
# Function to display nodes of DLLdef printList(head):         while(head):                 # Print the data        print(head.data, end = " ")        head = head.rightÂ
# Driver Codeif __name__ == '__main__':         # Given Binary Tree    root = newNode(1)    root.left = newNode(2)    root.right = newNode(3)    root.left.left = newNode(4)    root.left.right = newNode(5)    root.right.right = newNode(6)    root.left.left.left = newNode(7)    root.left.left.right = newNode(8)    root.right.right.left = newNode(9)    root.right.right.right = newNode(10)Â
    # Function Call to extract leaf Node    root = extractLeafList(root)Â
    # Function Call to create Balanced BT    root = sortedListToBST()Â
    # Print Inorder traversal New Balanced BT    print1(root)Â
# This code is contributed by ipg2016107 |
C#
// C# program for the above approachusing System;Â
class GFG{Â
// Structure for Linked // list and treepublic class Node {    public int data;    public Node left, right;};   static Node head;   // Function that returns the // count of nodes in the given // linked liststatic int countNodes(Node head){         // Initialize count    int count = 0;         Node temp = head;         // Iterate till the     // end of LL    while (temp != null)     {        temp = temp.right;                 // Increment the count        count++;    }         // Return the readonly count    return count;}Â
// Function to return the root of// the newly created balanced binary// tree from the given doubly LLstatic Node sortedListToBSTRecur(int n){         // Base Case    if (n <= 0)        return null;         // Recursively construct    // the left subtree    Node left = sortedListToBSTRecur(n / 2);         // head now refers to    // middle node, make     // middle node as root of BST    Node root = head;         // Set pointer to left subtree    root.left = left;         // Change head pointer of    // Linked List for parent    // recursive calls    head = head.right;         // Recursively construct the    // right subtree and link it    // with root    root.right = sortedListToBSTRecur(n - n /                                       2 - 1);         // Return the root     // of Balanced BT    return root;}   static Node sortedListToBST(){         // Count the number of     // nodes in Linked List    int n = countNodes(head);         // Construct BST    return sortedListToBSTRecur(n);}Â
// Function to find the leaf nodes and// make the doubly linked list of// those nodesstatic Node extractLeafList(Node root){         // Base cases    if (root == null)        return null;         if (root.left == null &&         root.right == null)     {                 // This node is added to doubly        // linked list of leaves, and        // set right pointer of this        // node as previous head of DLL        root.right = head;                 // Change left pointer        // of previous head        if (head != null)            head.left = root;                 // Change head of linked list        head = root;                 // Return new root        return head;    }         // Recur for right &     // left subtrees    root.right = extractLeafList(                 root.right);    root.left = extractLeafList(                root.left);         // Return the root    return root;}Â
// Function to allocating new // Node int Binary Treestatic Node newNode(int data){Â Â Â Â Node node = new Node();Â Â Â Â node.data = data;Â Â Â Â node.left = null;Â Â Â Â node.right = null;Â Â Â Â return node;}Â
// Function for inorder traversalstatic void print(Node root){         // If root is not null    if (root != null)     {        print(root.left);                 // Print the root's data        Console.Write(root.data + " ");        print(root.right);    }}Â
// Function to display nodes of DLLstatic void printList(Node head){    while (head != null)     {                 // Print the data        Console.Write(head.data + " ");        head = head.right;    }}Â
// Driver Codepublic static void Main(String[] args){         // Given Binary Tree    head = null;    Node root = newNode(1);         root.left = newNode(2);    root.right = newNode(3);    root.left.left = newNode(4);    root.left.right = newNode(5);    root.right.right = newNode(6);    root.left.left.left = newNode(7);    root.left.left.right = newNode(8);    root.right.right.left = newNode(9);    root.right.right.right = newNode(10);         // Function call to     // extract leaf Node    root = extractLeafList(root);         // Function call to create     // Balanced BT    root = sortedListToBST();         // Print Inorder traversal     // New Balanced BT    print(root);}}Â
// This code is contributed by Amit Katiyar |
Javascript
<script>    // Javascript program for the above approach         // Structure for Linked    // list and tree    class Node    {        constructor(data) {           this.left = null;           this.right = null;           this.data = data;        }    }Â
    let head;Â
    // Function that returns the    // count of nodes in the given    // linked list    function countNodes(head)    {      // Initialize count      let count = 0;Â
      let temp = head;Â
      // Iterate till the      // end of LL      while (temp != null)      {        temp = temp.right;Â
        // Increment the count        count++;      }Â
      // Return the final count      return count;    }Â
    // Function to return the root of    // the newly created balanced binary    // tree from the given doubly LL    function sortedListToBSTRecur(n)    {      // Base Case      if (n <= 0)        return null;Â
      // Recursively construct      // the left subtree      let left = sortedListToBSTRecur(parseInt(n / 2, 10));Â
      // head now refers to      // middle node, make      // middle node as root of BST      let root = head;Â
      // Set pointer to left subtree      root.left = left;Â
      // Change head pointer of      // Linked List for parent      // recursive calls      head = head.right;Â
      // Recursively construct the      // right subtree and link it      // with root      root.right = sortedListToBSTRecur(n - parseInt(n / 2, 10) - 1);Â
      // Return the root      // of Balanced BT      return root;    }Â
    function sortedListToBST()    {      // Count the number of      // nodes in Linked List      let n = countNodes(head);Â
      // Construct BST      return sortedListToBSTRecur(n);    }Â
    // Function to find the leaf nodes and    // make the doubly linked list of    // those nodes    function extractLeafList(root)    {      // Base cases      if (root == null)        return null;Â
      if (root.left == null &&          root.right == null)      {        // This node is added to doubly        // linked list of leaves, and        // set right pointer of this        // node as previous head of DLL        root.right = head;Â
        // Change left pointer        // of previous head        if (head != null)          head.left = root;Â
        // Change head of linked list        head = root;Â
        // Return new root        return head;      }Â
      // Recur for right &      // left subtrees      root.right =           extractLeafList(root.right);      root.left =           extractLeafList(root.left);Â
      // Return the root      return root;    }Â
    // Function to allocating new    // Node int Binary Tree    function newNode(data)    {      let node = new Node(data);      return node;    }Â
    // Function for inorder traversal    function print(root)    {      // If root is not null      if (root != null)      {        print(root.left);Â
        // Print the root's data        document.write(root.data + " ");        print(root.right);      }    }Â
    // Function to display nodes of DLL    function printList(head)    {      while (head != null)      {        // Print the data        document.write(head.data + " ");        head = head.right;      }    }         // Given Binary Tree    head = null;    let root = newNode(1);Â
    root.left = newNode(2);    root.right = newNode(3);    root.left.left = newNode(4);    root.left.right = newNode(5);    root.right.right = newNode(6);    root.left.left.left = newNode(7);    root.left.left.right = newNode(8);    root.right.right.left = newNode(9);    root.right.right.right = newNode(10);Â
    // Function Call to    // extract leaf Node    root = extractLeafList(root);Â
    // Function Call to create    // Balanced BT    root = sortedListToBST();Â
    // Print Inorder traversal    // New Balanced BT    print(root);   // This code is contributed by mukesh07.</script> |
Output:Â
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)
Â
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!




