Skip to content
Related Articles

Related Articles

Construct a complete binary tree from given array in level order fashion

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 15 Jul, 2022
Improve Article
Save Article

Given an array of elements, our task is to construct a complete binary tree from this array in a level order fashion. That is, elements from the left in the array will be filled in the tree level-wise starting from level 0.
Examples: 
 

Input  :  arr[] = {1, 2, 3, 4, 5, 6}
Output : Root of the following tree
                  1
                 / \
                2   3
               / \ /
              4  5 6


Input: arr[] = {1, 2, 3, 4, 5, 6, 6, 6, 6, 6}
Output: Root of the following tree
                   1
                  / \
                 2   3
                / \ / \
               4  5 6  6
              / \ /
             6  6 6

 

If we observe carefully we can see that if the parent node is at index i in the array then the left child of that node is at index (2*i + 1) and the right child is at index (2*i + 2) in the array. 
Using this concept, we can easily insert the left and right nodes by choosing their parent node. We will insert the first element present in the array as the root node at level 0 in the tree and start traversing the array and for every node, we will insert both children left and right in the tree. 
Below is the recursive program to do this: 
 

C++




// CPP program to construct binary 
// tree from given array in level
// order fashion Tree Node
#include <bits/stdc++.h>
using namespace std;
  
/* A binary tree node has data, 
pointer to left child and a
pointer to right child */
struct Node
{
    int data;
    Node* left, * right;
};
  
/* Helper function that allocates a
new node */
Node* newNode(int data)
{
    Node* node = (Node*)malloc(sizeof(Node));
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
  
// Function to insert nodes in level order
Node* insertLevelOrder(int arr[],
                       int i, int n)
{
      Node *root = nullptr;
    // Base case for recursion
    if (i < n)
    {
        root = newNode(arr[i]);
          
        // insert left child
        root->left = insertLevelOrder(arr,
                   2 * i + 1, n);
  
        // insert right child
        root->right = insertLevelOrder(arr,
                  2 * i + 2, n);
    }
    return root;
}
  
// Function to print tree nodes in
// InOrder fashion
void inOrder(Node* root)
{
    if (root != NULL)
    {
        inOrder(root->left);
        cout << root->data <<" ";
        inOrder(root->right);
    }
}
  
// Driver program to test above function
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 6, 6, 6 };
    int n = sizeof(arr)/sizeof(arr[0]);
    Node* root = insertLevelOrder(arr, 0, n);
    inOrder(root);
}
  
// This code is contributed by Chhavi and improved by Thangaraj


Java




// Java program to construct binary tree from
// given array in level order fashion
  
public class Tree {
    Node root;
  
    // Tree Node
    static class Node {
        int data;
        Node left, right;
        Node(int data)
        {
            this.data = data;
            this.left = null;
            this.right = null;
        }
    }
  
    // Function to insert nodes in level order
    public Node insertLevelOrder(int[] arr, int i)
    {
          Node root = null;
        // Base case for recursion
        if (i < arr.length) {
            root = new Node(arr[i]);
  
            // insert left child
            root.left = insertLevelOrder(arr, 2 * i + 1);
  
            // insert right child
            root.right = insertLevelOrder(arr, 2 * i + 2);
        }
        return root;
    }
  
    // Function to print tree nodes in InOrder fashion
    public void inOrder(Node root)
    {
        if (root != null) {
            inOrder(root.left);
            System.out.print(root.data + " ");
            inOrder(root.right);
        }
    }
  
    // Driver program to test above function
    public static void main(String args[])
    {
        Tree t2 = new Tree();
        int arr[] = { 1, 2, 3, 4, 5, 6, 6, 6, 6 };
        t2.root = t2.insertLevelOrder(arr, 0);
        t2.inOrder(t2.root);
    }
}


Python3




# Python3 program to construct binary 
# tree from given array in level 
# order fashion Tree Node 
  
# Helper function that allocates a 
#new node
class newNode:
    def __init__(self, data):
        self.data = data 
        self.left = self.right = None
  
# Function to insert nodes in level order 
def insertLevelOrder(arr, i, n):
    root = None
    # Base case for recursion 
    if i < n:
        root = newNode(arr[i]) 
  
        # insert left child 
        root.left = insertLevelOrder(arr, 2 * i + 1, n)
  
        # insert right child 
        root.right = insertLevelOrder(arr, 2 * i + 2, n)
          
    return root
  
# Function to print tree nodes in 
# InOrder fashion 
def inOrder(root):
    if root != None:
        inOrder(root.left) 
        print(root.data,end=" "
        inOrder(root.right)
  
# Driver Code
if __name__ == '__main__':
    arr = [1, 2, 3, 4, 5, 6, 6, 6, 6]
    n = len(arr)
    root = None
    root = insertLevelOrder(arr, 0, n) 
    inOrder(root)
      
# This code is contributed by PranchalK and Improved by Thangaraj


C#




// C# program to construct binary tree from
// given array in level order fashion
using System;
      
public class Tree
{
    Node root;
  
    // Tree Node
    public class Node 
    {
        public int data;
        public Node left, right;
        public Node(int data)
        {
            this.data = data;
            this.left = null;
            this.right = null;
        }
    }
  
    // Function to insert nodes in level order
    public Node insertLevelOrder(int[] arr, int i)
    {
          Node root = null;
        // Base case for recursion
        if (i < arr.Length) 
        {
            root = new Node(arr[i]);
  
            // insert left child
            root.left = insertLevelOrder(arr, 2 * i + 1);
  
            // insert right child
            root.right = insertLevelOrder(arr, 2 * i + 2);
        }
        return root;
    }
  
    // Function to print tree
    // nodes in InOrder fashion
    public void inOrder(Node root)
    {
        if (root != null
        {
            inOrder(root.left);
            Console.Write(root.data + " ");
            inOrder(root.right);
        }
    }
  
    // Driver code
    public static void Main(String []args)
    {
        Tree t2 = new Tree();
        int []arr = { 1, 2, 3, 4, 5, 6, 6, 6, 6 };
        t2.root = t2.insertLevelOrder(arr, 0);
        t2.inOrder(t2.root);
    }
}
  
// This code is contributed Rajput-Ji and improved by Thangaraj


Javascript




<script>
    // Javascript program to construct binary tree from
    // given array in level order fashion
      
    let root;
      
    class Node
    {
        constructor(data) {
           this.left = null;
           this.right = null;
           this.data = data;
        }
    }
      
    // Function to insert nodes in level order
    function insertLevelOrder(arr, i)
    {
        let root = null;
        // Base case for recursion
        if (i < arr.length) {
            root = new Node(arr[i]);
    
            // insert left child
            root.left = insertLevelOrder(arr, 2 * i + 1);
    
            // insert right child
            root.right = insertLevelOrder(arr, 2 * i + 2);
        }
        return root;
    }
    
    // Function to print tree nodes in InOrder fashion
    function inOrder(root)
    {
        if (root != null) {
            inOrder(root.left);
            document.write(root.data + " ");
            inOrder(root.right);
        }
    }
      
    let arr = [ 1, 2, 3, 4, 5, 6, 6, 6, 6 ];
    root = insertLevelOrder(arr, 0);
    inOrder(root);
  
// This code is contributed by suresh07 and improved by Thangaraj
</script>


Output

6 4 6 2 5 1 6 3 6 

Time Complexity: O(n), where n is the total number of nodes in the tree. 

Space Complexity: O(n) for calling recursion using stack.
 

This article is contributed by Haribalaji R. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.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.
 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!