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++
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node* left, * right;
};
Node* newNode( int data)
{
Node* node = (Node*) malloc ( sizeof (Node));
node->data = data;
node->left = node->right = NULL;
return (node);
}
Node* insertLevelOrder( int arr[],
int i, int n)
{
Node *root = nullptr;
if (i < n)
{
root = newNode(arr[i]);
root->left = insertLevelOrder(arr,
2 * i + 1, n);
root->right = insertLevelOrder(arr,
2 * i + 2, n);
}
return root;
}
void inOrder(Node* root)
{
if (root != NULL)
{
inOrder(root->left);
cout << root->data << " " ;
inOrder(root->right);
}
}
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);
}
|
Java
public class Tree {
Node root;
static class Node {
int data;
Node left, right;
Node( int data)
{
this .data = data;
this .left = null ;
this .right = null ;
}
}
public Node insertLevelOrder( int [] arr, int i)
{
Node root = null ;
if (i < arr.length) {
root = new Node(arr[i]);
root.left = insertLevelOrder(arr, 2 * i + 1 );
root.right = insertLevelOrder(arr, 2 * i + 2 );
}
return root;
}
public void inOrder(Node root)
{
if (root != null ) {
inOrder(root.left);
System.out.print(root.data + " " );
inOrder(root.right);
}
}
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
class newNode:
def __init__( self , data):
self .data = data
self .left = self .right = None
def insertLevelOrder(arr, i, n):
root = None
if i < n:
root = newNode(arr[i])
root.left = insertLevelOrder(arr, 2 * i + 1 , n)
root.right = insertLevelOrder(arr, 2 * i + 2 , n)
return root
def inOrder(root):
if root ! = None :
inOrder(root.left)
print (root.data,end = " " )
inOrder(root.right)
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)
|
C#
using System;
public class Tree
{
Node root;
public class Node
{
public int data;
public Node left, right;
public Node( int data)
{
this .data = data;
this .left = null ;
this .right = null ;
}
}
public Node insertLevelOrder( int [] arr, int i)
{
Node root = null ;
if (i < arr.Length)
{
root = new Node(arr[i]);
root.left = insertLevelOrder(arr, 2 * i + 1);
root.right = insertLevelOrder(arr, 2 * i + 2);
}
return root;
}
public void inOrder(Node root)
{
if (root != null )
{
inOrder(root.left);
Console.Write(root.data + " " );
inOrder(root.right);
}
}
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);
}
}
|
Javascript
<script>
let root;
class Node
{
constructor(data) {
this .left = null ;
this .right = null ;
this .data = data;
}
}
function insertLevelOrder(arr, i)
{
let root = null ;
if (i < arr.length) {
root = new Node(arr[i]);
root.left = insertLevelOrder(arr, 2 * i + 1);
root.right = insertLevelOrder(arr, 2 * i + 2);
}
return root;
}
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);
</script>
|
Time Complexity: O(n), where n is the total number of nodes in the tree.
Space Complexity: O(n) for calling recursion using stack.
Approach 2: Using queue
Create a TreeNode struct to represent a node in the binary tree.
Define a function buildTree that takes the nums array as a parameter.
If the nums array is empty, return NULL.
Create the root node with the value at index 0 and push it into a queue.
Initialize an integer i to 1.
Loop while the queue is not empty:
Pop the front node from the queue and assign it to curr.
If i is less than the size of the nums array, create a new node with the value at index i and set it as the left child of curr. Increment i by 1. Push the left child node into the queue.
If i is less than the size of the nums array, create a new node with the value at index i and set it as the right child of curr. Increment i by 1. Push the right child node into the queue.
Return the root node.
Define a printTree function to print the values of the tree in preorder traversal order.
Call the buildTree function with the given nums array to construct the complete binary tree.
Call the printTree function to print the values of the tree.
Time complexity: The buildTree function has to visit every element in the nums array once, so the time complexity is O(n), where n is the size of the nums array.
C++
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode( int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* buildTree(vector< int >& nums) {
if (nums.empty()) {
return NULL;
}
TreeNode* root = new TreeNode(nums[0]);
queue<TreeNode*> q;
q.push(root);
int i = 1;
while (i < nums.size()) {
TreeNode* curr = q.front();
q.pop();
if (i < nums.size()) {
curr->left = new TreeNode(nums[i++]);
q.push(curr->left);
}
if (i < nums.size()) {
curr->right = new TreeNode(nums[i++]);
q.push(curr->right);
}
}
return root;
}
void printTree(TreeNode* root) {
if (!root) {
return ;
}
printTree(root->left);
cout << root->val << " " ;
printTree(root->right);
}
int main() {
vector< int > nums = { 1, 2, 3, 4, 5, 6, 6, 6, 6 };
TreeNode* root = buildTree(nums);
printTree(root);
return 0;
}
|
Java
import java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode( int x) {
val = x;
left = null ;
right = null ;
}
}
class Main {
public static TreeNode buildTree( int [] nums) {
if (nums == null || nums.length == 0 ) {
return null ;
}
TreeNode root = new TreeNode(nums[ 0 ]);
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
int i = 1 ;
while (i < nums.length) {
TreeNode curr = q.remove();
if (i < nums.length) {
curr.left = new TreeNode(nums[i++]);
q.add(curr.left);
}
if (i < nums.length) {
curr.right = new TreeNode(nums[i++]);
q.add(curr.right);
}
}
return root;
}
public static void printTree(TreeNode root) {
if (root == null ) {
return ;
}
printTree(root.left);
System.out.print(root.val + " " );
printTree(root.right);
}
public static void main(String[] args) {
int [] nums = { 1 , 2 , 3 , 4 , 5 , 6 , 6 , 6 , 6 };
TreeNode root = buildTree(nums);
printTree(root);
}
}
|
Python3
class TreeNode:
def __init__( self , x):
self .val = x
self .left = None
self .right = None
def buildTree(nums):
if not nums:
return None
root = TreeNode(nums[ 0 ])
q = [root]
i = 1
while i < len (nums):
curr = q.pop( 0 )
if i < len (nums):
curr.left = TreeNode(nums[i])
q.append(curr.left)
i + = 1
if i < len (nums):
curr.right = TreeNode(nums[i])
q.append(curr.right)
i + = 1
return root
def printTree(root):
if not root:
return
printTree(root.left)
print (root.val, end = " " )
printTree(root.right)
nums = [ 1 , 2 , 3 , 4 , 5 , 6 , 6 , 6 , 6 ]
root = buildTree(nums)
printTree(root)
|
C#
using System;
using System.Collections.Generic;
public class TreeNode
{
public int val;
public TreeNode left, right;
public TreeNode( int x)
{
val = x;
left = null ;
right = null ;
}
}
public class MainClass
{
public static TreeNode BuildTree( int [] nums)
{
if (nums == null || nums.Length == 0)
{
return null ;
}
TreeNode root = new TreeNode(nums[0]);
Queue<TreeNode> q = new Queue<TreeNode>();
q.Enqueue(root);
int i = 1;
while (i < nums.Length)
{
TreeNode curr = q.Dequeue();
if (i < nums.Length)
{
curr.left = new TreeNode(nums[i++]);
q.Enqueue(curr.left);
}
if (i < nums.Length)
{
curr.right = new TreeNode(nums[i++]);
q.Enqueue(curr.right);
}
}
return root;
}
public static void PrintTree(TreeNode root)
{
if (root == null )
{
return ;
}
PrintTree(root.left);
Console.Write(root.val + " " );
PrintTree(root.right);
}
public static void Main( string [] args)
{
int [] nums = { 1, 2, 3, 4, 5, 6, 6, 6, 6 };
TreeNode root = BuildTree(nums);
PrintTree(root);
}
}
|
Javascript
class TreeNode {
constructor(val) {
this .val = val;
this .left = null ;
this .right = null ;
}
}
function buildTree(nums) {
if (nums.length === 0) {
return null ;
}
let root = new TreeNode(nums[0]);
let q = [root];
let i = 1;
while (i < nums.length) {
let curr = q.shift();
if (i < nums.length) {
curr.left = new TreeNode(nums[i++]);
q.push(curr.left);
}
if (i < nums.length) {
curr.right = new TreeNode(nums[i++]);
q.push(curr.right);
}
}
return root;
}
function printTree(root) {
if (!root) {
return ;
}
printTree(root.left);
console.log(root.val + " " );
printTree(root.right);
}
let nums = [1, 2, 3, 4, 5, 6, 6, 6, 6];
let root = buildTree(nums);
printTree(root);
|
Time Complexity: O(n), where n is the total number of nodes in the tree.
Auxiliary Space: O(n)
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.
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 geeks!
Last Updated :
05 Oct, 2023
Like Article
Save Article