Construya un árbol binario completo a partir de una array dada en orden de nivel

Dada una array de elementos, nuestra tarea es construir un árbol binario completo a partir de esta array en orden de niveles. Es decir, los elementos de la izquierda en la array se completarán en el árbol por niveles a partir del nivel 0.
Ejemplos: 
 

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

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>

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *