Construct a complete binary tree from given array in level order fashion
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
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.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.
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++
// 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
// Java program to construct binary tree from// given array in level order fashionpublic 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
# 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#
// 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 |
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, 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.
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.



