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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem