Given an array of integers, the task is to construct a binary tree in level order fashion using Recursion.
Examples
Given an array arr[] = {15, 10, 20, 8, 12, 16, 25}
Approach:
Idea is to keep track of the number of child nodes in the left sub-tree and right sub-tree and then take the decision on the basis of these counts.
- When the count of children nodes in left and right sub-tree are equal, then the node has to be inserted in left sub-tree by creating a new level in the binary tree.
- When the count of children nodes in the left sub-tree is greater than the count of the children nodes in the right sub-tree then there are two cases.
- When the left sub-tree is perfect binary tree, then node is to be inserted in right sub-tree.
- When left sub-tree is not perfect binary tree, then node is to be inserted in left sub-tree.
A perfect binary tree with n levels have 2(n-1) nodes with all the leaf nodes at same level.
Below is the implementation of the above approach
C++
// C++ implementation to construct// Binary Tree in level order fashion#include <iostream>using namespace std;// Structure of the Node of Binary tree// with count of Children nodes in // left sub-tree and right sub-tree.struct Node { int data; int rcount; int lcount; struct Node* left; struct Node* right;};// Function to check whether the given// Binary tree is a perfect binary tree// using the no. of nodes in tree.bool isPBT(int count){ count = count + 1; // Loop to check the count is in // the form of 2^(n-1) while (count % 2 == 0) count = count / 2; if (count == 1) return true; else return false;}// Function to create a new Nodestruct Node* newNode(int data){ struct Node* temp = (struct Node*)malloc( sizeof(struct Node) ); temp->data = data; temp->right = NULL; temp->left = NULL; temp->rcount = 0; temp->lcount = 0;}// Recursive function to insert// elements in a binary treestruct Node* insert(struct Node* root, int data){ // Condition when root is NULL if (root == NULL) { struct Node* n = newNode(data); return n; } // Condition when count of left sub-tree // nodes is equal to the count // of right sub-tree nodes if (root->rcount == root->lcount) { root->left = insert(root->left, data); root->lcount += 1; } // Condition when count of left sub-tree // nodes is greater than // the right sub-tree nodes else if (root->rcount < root->lcount) { // Condition when left Sub-tree is // Perfect Binary Tree then Insert // in right sub-tree. if (isPBT(root->lcount)) { root->right = insert(root->right, data); root->rcount += 1; } // If Left Sub-tree is not Perfect // Binary Tree then Insert in left sub-tree else { root->left = insert(root->left, data); root->lcount += 1; } } return root;}// Function for inorder Traversal of tree.void inorder(struct Node* root){ if (root != NULL) { inorder(root->left); cout << root->data << " "; inorder(root->right); }}// Driver Codeint main(){ int arr[] = { 8, 6, 7, 12, 5, 1, 9 }; int size = sizeof(arr) / sizeof(int); struct Node* root = NULL; // Loop to insert nodes in // Binary Tree in level order for (int i = 0; i < size; i++) root = insert(root, arr[i]); inorder(root); return 0;} |
Java
// Java implementation to construct// Binary Tree in level order fashionclass Node { int data; int rcount; int lcount; Node left; Node right; Node(int data) { this.data = data; this.rcount = this.lcount = 0; this.left = this.right = null; } // Function for inorder Traversal of tree. static void inorder(Node root) { if (root != null) { inorder(root.left); System.out.print(root.data + " "); inorder(root.right); } } // Function to check whether the given // Binary tree is a perfect binary tree // using the no. of nodes in tree. static boolean isPBT(int count) { count = count + 1; // Loop to check the count is in // the form of 2^(n-1) while (count % 2 == 0) count = count / 2; if (count == 1) return true; else return false; } // Recursive function to insert // elements in a binary tree static Node insert(Node root, int data) { // Condition when root is NULL if (root == null) { Node n = new Node(data); return n; } // Condition when count of left sub-tree // nodes is equal to the count // of right sub-tree nodes if (root.rcount == root.lcount) { root.left = insert(root.left, data); root.lcount += 1; } // Condition when count of left sub-tree // nodes is greater than // the right sub-tree nodes else if (root.rcount < root.lcount) { // Condition when left Sub-tree is // Perfect Binary Tree then Insert // in right sub-tree. if (isPBT(root.lcount)) { root.right = insert(root.right, data); root.rcount += 1; } // If Left Sub-tree is not Perfect // Binary Tree then Insert in left sub-tree else { root.left = insert(root.left, data); root.lcount += 1; } } return root; } // Driver Code public static void main(String args[]) { int arr[] = { 8, 6, 7, 12, 5, 1, 9 }; int size = 7; Node root = null; // Loop to insert nodes in // Binary Tree in level order Traversal for (int i = 0; i < size; i++) root = insert(root, arr[i]); inorder(root); }} |
Python3
# Python3 implementation to construct# Binary Tree in level order fashion# Structure of the Node of Binary tree# with count of Children nodes in# left sub-tree and right sub-tree.class Node: def __init__(self, data): self.data = data self.rcount = 0 self.lcount = 0 self.left = None self.right = None# Function to check whether the given# Binary tree is a perfect binary tree# using the no. of nodes in tree.def isPBT(count: int) -> bool: count = count + 1 # Loop to check the count is in # the form of 2^(n-1) while (count % 2 == 0): count = count / 2 if (count == 1): return True else: return False# Recursive function to insert# elements in a binary treedef insert(root: Node, data: int) -> Node: # Condition when root is NULL if (root is None): n = Node(data) return n # Condition when count of left sub-tree # nodes is equal to the count # of right sub-tree nodes if (root.rcount == root.lcount): root.left = insert(root.left, data) root.lcount += 1 # Condition when count of left sub-tree # nodes is greater than # the right sub-tree nodes elif (root.rcount < root.lcount): # Condition when left Sub-tree is # Perfect Binary Tree then Insert # in right sub-tree. if (isPBT(root.lcount)): root.right = insert(root.right, data) root.rcount += 1 # If Left Sub-tree is not Perfect # Binary Tree then Insert in left sub-tree else: root.left = insert(root.left, data) root.lcount += 1 return root# Function for inorder Traversal of tree.def inorder(root: Node) -> None: if root != None: inorder(root.left) print(root.data, end = " ") inorder(root.right)# Driver Codeif __name__ == "__main__": arr = [ 8, 6, 7, 12, 5, 1, 9 ] size = len(arr) root = None # Loop to insert nodes in # Binary Tree in level order for i in range(size): root = insert(root, arr[i]) inorder(root)# This code is contributed by sanjeev2552 |
C#
// C# implementation to construct// Binary Tree in level order fashionusing System;class Node { public int data; public int rcount; public int lcount; public Node left; public Node right; public Node(int data) { this.data = data; this.rcount = this.lcount = 0; this.left = this.right = null; } // Function for inorder Traversal of tree. static void inorder(Node root) { if (root != null) { inorder(root.left); Console.Write(root.data + " "); inorder(root.right); } } // Function to check whether the given // Binary tree is a perfect binary tree // using the no. of nodes in tree. static bool isPBT(int count) { count = count + 1; // Loop to check the count is in // the form of 2^(n-1) while (count % 2 == 0) count = count / 2; if (count == 1) return true; else return false; } // Recursive function to insert // elements in a binary tree static Node insert(Node root, int data) { // Condition when root is NULL if (root == null) { Node n = new Node(data); return n; } // Condition when count of left sub-tree // nodes is equal to the count // of right sub-tree nodes if (root.rcount == root.lcount) { root.left = insert(root.left, data); root.lcount += 1; } // Condition when count of left sub-tree // nodes is greater than // the right sub-tree nodes else if (root.rcount < root.lcount) { // Condition when left Sub-tree is // Perfect Binary Tree then Insert // in right sub-tree. if (isPBT(root.lcount)) { root.right = insert(root.right, data); root.rcount += 1; } // If Left Sub-tree is not Perfect // Binary Tree then Insert in left sub-tree else { root.left = insert(root.left, data); root.lcount += 1; } } return root; } // Driver Code public static void Main(String []args) { int []arr = { 8, 6, 7, 12, 5, 1, 9 }; int size = 7; Node root = null; // Loop to insert nodes in // Binary Tree in level order Traversal for (int i = 0; i < size; i++) root = insert(root, arr[i]); inorder(root); }}// This code is contributed by 29AjayKumar |
12 6 5 8 1 7 9
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
- Construct a complete binary tree from given array in level order fashion
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Flatten Binary Tree in order of Level Order Traversal
- Construct a tree from Inorder and Level order traversals | Set 1
- Construct BST from its given level order traversal
- Construct a tree from Inorder and Level order traversals | Set 2
- Construct BST from its given level order traversal | Set-2
- Connect Nodes at same Level (Level Order Traversal)
- Find Maximum Level Sum in Binary Tree using Recursion
- Insertion in n-ary tree in given order and Level order traversal
- Difference between sums of odd level and even level nodes of a Binary Tree
- Print the nodes corresponding to the level value for each level of a Binary Tree
- Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree
- Density of Binary Tree using Level Order Traversal
- Calculate height of Binary Tree using Inorder and Level Order Traversal
- Level order traversal of Binary Tree using Morris Traversal
- Deletion of a given node K in a Binary Tree using Level Order Traversal
- Product of nodes at k-th level in a tree represented as string using Recursion
- Perfect Binary Tree Specific Level Order Traversal
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


