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

30 Jun, 2021
Given an array of elements, our task is to construct a complete binary tree from this array in level order fashion. That is, elements from 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 parent node is at index i in the array then the left child of that node is at index (2*i + 1) and 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 its 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 i we will insert its both childs left and right in the tree. Below is the recursive program to do this:  
C++
Java
Python3
C#
Javascript
// 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 apointer to right child */struct Node{    int data;    Node* left, * right;}; /* Helper function that allocates anew 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 orderNode* insertLevelOrder(int arr[], Node* root,                       int i, int n){    // Base case for recursion    if (i < n)    {        Node* temp = newNode(arr[i]);        root = temp;         // insert left child        root->left = insertLevelOrder(arr,                   root->left, 2 * i + 1, n);         // insert right child        root->right = insertLevelOrder(arr,                  root->right, 2 * i + 2, n);    }    return root;} // Function to print tree nodes in// InOrder fashionvoid inOrder(Node* root){    if (root != NULL)    {        inOrder(root->left);        cout << root->data <<" ";        inOrder(root->right);    }} // Driver program to test above functionint main(){    int arr[] = { 1, 2, 3, 4, 5, 6, 6, 6, 6 };    int n = sizeof(arr)/sizeof(arr[0]);    Node* root = insertLevelOrder(arr, root, 0, n);    inOrder(root);} // This code is contributed by Chhavi
// 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, Node root,                                                int i)    {        // Base case for recursion        if (i < arr.length) {            Node temp = new Node(arr[i]);            root = temp;             // insert left child            root.left = insertLevelOrder(arr, root.left,                                             2 * i + 1);             // insert right child            root.right = insertLevelOrder(arr, root.right,                                               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, t2.root, 0);        t2.inOrder(t2.root);    }}
# Python3 program to construct binary# tree from given array in level# order fashion Tree Node # Helper function that allocates a#new nodeclass newNode:    def __init__(self, data):        self.data = data        self.left = self.right = None # Function to insert nodes in level orderdef insertLevelOrder(arr, root, i, n):         # Base case for recursion    if i < n:        temp = newNode(arr[i])        root = temp         # insert left child        root.left = insertLevelOrder(arr, root.left,                                     2 * i + 1, n)         # insert right child        root.right = insertLevelOrder(arr, root.right,                                      2 * i + 2, n)    return root # Function to print tree nodes in# InOrder fashiondef inOrder(root):    if root != None:        inOrder(root.left)        print(root.data,end=" ")        inOrder(root.right) # Driver Codeif __name__ == '__main__':    arr = [1, 2, 3, 4, 5, 6, 6, 6, 6]    n = len(arr)    root = None    root = insertLevelOrder(arr, root, 0, n)    inOrder(root)     # This code is contributed by PranchalK
// C# program to construct binary tree from// given array in level order fashionusing 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,                            Node root, int i)    {        // Base case for recursion        if (i < arr.Length)        {            Node temp = new Node(arr[i]);            root = temp;             // insert left child            root.left = insertLevelOrder(arr,                            root.left, 2 * i + 1);             // insert right child            root.right = insertLevelOrder(arr,                            root.right, 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, t2.root, 0);        t2.inOrder(t2.root);    }} // This code is contributed Rajput-Ji
<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, root, i)    {        // Base case for recursion        if (i < arr.length) {            let temp = new Node(arr[i]);            root = temp;               // insert left child            root.left = insertLevelOrder(arr, root.left,                                             2 * i + 1);               // insert right child            root.right = insertLevelOrder(arr, root.right,                                               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, root, 0);    inOrder(root); // This code is contributed by suresh07.</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.  
YouTubeGeeksforGeeks507K subscribersConstruct a complete binary tree from given array in level order fashion | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:37•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=k14dvCPsn3Q" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
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. 
PranchalKatiyar
Rajput-Ji
suresh07
tree-level-order
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Binary Tree | Set 2 (Properties)
Decision Tree
Introduction to Tree Data Structure
Lowest Common Ancestor in a Binary Tree | Set 1
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Expression Tree
Deletion in a Binary Tree
Binary Tree (Array implementation)
BFS vs DFS for Binary Tree
AVL Tree | Set 2 (Deletion)