Related Articles

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

• Difficulty Level : Easy
• Last Updated : 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++

 `// CPP program to construct binary``// tree from given array in level``// order fashion Tree Node``#include ``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[], 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 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);``    ``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 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

 `# 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, 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 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, root, ``0``, n)``    ``inOrder(root)``    ` `# This code is contributed by PranchalK`

## 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,``                            ``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

 ``

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.