Construct a complete binary tree from given array in level order fashion | CPP program to construct binary tree from given array in level order fashion Tree Node ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node ; Function to insert nodes in level order ; Base case for recursion ; insert left child ; insert right child ; Function to print tree nodes in InOrder fashion ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) { Node * node = ( Node * ) malloc ( sizeof ( Node ) ) ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } Node * insertLevelOrder ( int arr [ ] , Node * root , int i , int n ) { if ( i < n ) { Node * temp = newNode ( arr [ i ] ) ; root = temp ; root -> left = insertLevelOrder ( arr , root -> left , 2 * i + 1 , n ) ; root -> right = insertLevelOrder ( arr , root -> right , 2 * i + 2 , n ) ; } return root ; } void inOrder ( Node * root ) { if ( root != NULL ) { inOrder ( root -> left ) ; cout << root -> data << " ▁ " ; inOrder ( root -> right ) ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 6 , 6 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; Node * root = insertLevelOrder ( arr , root , 0 , n ) ; inOrder ( root ) ; }