Saturday, December 28, 2024
Google search engine
HomeData Modelling & AIConstruct a complete binary tree from given array in level order fashion

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

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


Python3




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


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)

This article is contributed by Haribalaji R. If you like neveropen 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 neveropen 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 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments