Construct a complete binary tree from given array in level order fashion
Last Updated :
09 Jan, 2025
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);
}
}
Python
# 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>
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);
}
}
Python
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;
// creating a tree node
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]);
// taking a queue
Queue<TreeNode> q = new Queue<TreeNode>();
q.Enqueue(root);
int i = 1;
while (i < nums.Length)
{
TreeNode curr = q.Dequeue();
if (i < nums.Length)
{
// traversing left
curr.left = new TreeNode(nums[i++]);
q.Enqueue(curr.left);
}
if (i < nums.Length)
{
// traversing right
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);
}
// Driver code
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)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands
SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read