Open In App

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

Last Updated : 09 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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 Python 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 Python 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.

Auxiliary Space: O(n)




 



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg