Open In App

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

Last Updated : 05 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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++





Java





Python3





C#





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. 

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;
 
// 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);


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.

Auxiliary Space: O(n)



 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads