Create a tree in level order
Given an array of elements, the task is to insert these elements in level order and construct a tree.
Input : arr[] = {10, 20, 30, 40, 50, 60}
Output : 10
/ \
20 30
/ \ /
40 50 60
The task is to construct a whole tree from a given array. To insert in level order in an already constructed tree, please see Insertion in a Binary Tree in level order
The task is to store data in a binary tree but in level order.
To do so, we will proceed as follows:
- Whenever a new Node is added to the binary tree, the address of the node is pushed into a queue.
- Node addresses will stay in the queue until both its children’s Nodes do not get filled.
- Once both the children’s Nodes get filled up, the parent Node is popped from the queue.
Here is the code to perform the above-mentioned data entry.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
Node* left;
Node* right;
};
struct Node* newNode( int value)
{
Node* n = new Node;
n->key = value;
n->left = NULL;
n->right = NULL;
return n;
}
struct Node* insertValue( struct Node* root, int value,
queue<Node *>& q)
{
Node* node = newNode(value);
if (root == NULL)
root = node;
else if (q.front()->left == NULL)
q.front()->left = node;
else {
q.front()->right = node;
q.pop();
}
q.push(node);
return root;
}
Node* createTree( int arr[], int n)
{
Node* root = NULL;
queue<Node*> q;
for ( int i = 0; i < n; i++)
root = insertValue(root, arr[i], q);
return root;
}
void levelOrder( struct Node* root)
{
if (root == NULL)
return ;
queue<Node*> n;
n.push(root);
while (!n.empty()) {
cout << n.front()->key << " " ;
if (n.front()->left != NULL)
n.push(n.front()->left);
if (n.front()->right != NULL)
n.push(n.front()->right);
n.pop();
}
}
int main()
{
int arr[] = { 10, 20, 30, 40, 50, 60 };
int n = sizeof (arr) / sizeof (arr[0]);
Node* root = createTree(arr, n);
levelOrder(root);
return 0;
}
|
Java
import java.util.*;
class GFG{
static class Node
{
int key;
Node left;
Node right;
};
static Node root = null ;
static Queue<Node> q =
new LinkedList<>();
static Node newNode( int value)
{
Node n = new Node();
n.key = value;
n.left = null ;
n.right = null ;
return n;
}
static void insertValue( int value)
{
Node node = newNode(value);
if (root == null )
root = node;
else if (q.peek().left == null )
q.peek().left = node;
else
{
q.peek().right = node;
q.remove();
}
q.add(node);
}
static void createTree( int arr[],
int n)
{
for ( int i = 0 ; i < n; i++)
insertValue(arr[i]);
}
static void levelOrder(Node root)
{
if (root == null )
return ;
Queue<Node> n =
new LinkedList<>();
n.add(root);
while (!n.isEmpty())
{
System.out.print(n.peek().key +
" " );
if (n.peek().left != null )
n.add(n.peek().left);
if (n.peek().right != null )
n.add(n.peek().right);
n.remove();
}
}
public static void main(String[] args)
{
int arr[] = { 10 , 20 , 30 ,
40 , 50 , 60 };
int n = arr.length;
createTree(arr, n);
levelOrder(root);
}
}
|
Python3
from collections import deque
class node:
def __init__( self , data = None ):
self .data = data
self .left = None
self .right = None
Q = deque()
def insertValue(data, root):
newnode = node(data)
if Q:
temp = Q[ 0 ]
if root = = None :
root = newnode
elif temp.left = = None :
temp.left = newnode
elif temp.right = = None :
temp.right = newnode
atemp = Q.popleft()
Q.append(newnode)
return root
def createTree(a, root):
for i in range ( len (a)):
root = insertValue(a[i], root)
return root
def levelOrder(root):
Q = deque()
Q.append(root)
while Q:
temp = Q.popleft()
print (temp.data, end = ' ' )
if temp.left ! = None :
Q.append(temp.left)
if temp.right ! = None :
Q.append(temp.right)
a = [ 10 , 20 , 30 , 40 , 50 , 60 ]
root = None
root = createTree(a, root)
levelOrder(root)
|
C#
using System;
using System.Collections.Generic;
class GFG {
class Node
{
public int key;
public Node left, right;
};
static Node root = null ;
static List<Node> q = new List<Node>();
static Node newNode( int value)
{
Node n = new Node();
n.key = value;
n.left = null ;
n.right = null ;
return n;
}
static void insertValue( int value)
{
Node node = newNode(value);
if (root == null )
root = node;
else if (q[0].left == null )
q[0].left = node;
else
{
q[0].right = node;
q.RemoveAt(0);
}
q.Add(node);
}
static void createTree( int [] arr, int n)
{
for ( int i = 0; i < n; i++)
insertValue(arr[i]);
}
static void levelOrder(Node root)
{
if (root == null )
return ;
List<Node> n = new List<Node>();
n.Add(root);
while (n.Count > 0)
{
Console.Write(n[0].key + " " );
if (n[0].left != null )
n.Add(n[0].left);
if (n[0].right != null )
n.Add(n[0].right);
n.RemoveAt(0);
}
}
static void Main() {
int [] arr = {10, 20, 30, 40, 50, 60};
int n = arr.Length;
createTree(arr, n);
levelOrder(root);
}
}
|
Javascript
<script>
class Node
{
constructor(value)
{
this .left = null ;
this .right = null ;
this .key = value;
}
}
let root = null ;
let q = [];
function newNode(value)
{
let n = new Node(value);
return n;
}
function insertValue(value)
{
let node = newNode(value);
if (root == null )
root = node;
else if (q[0].left == null )
q[0].left = node;
else
{
q[0].right = node;
q.shift();
}
q.push(node);
}
function createTree(arr, n)
{
for (let i = 0; i < n; i++)
insertValue(arr[i]);
}
function levelOrder(root)
{
if (root == null )
return ;
let n = [];
n.push(root);
while (n.length > 0)
{
document.write(n[0].key + " " );
if (n[0].left != null )
n.push(n[0].left);
if (n[0].right != null )
n.push(n[0].right);
n.shift();
}
}
let arr = [ 10, 20, 30, 40, 50, 60 ];
let n = arr.length;
createTree(arr, n);
levelOrder(root);
</script>
|
Time Complexity: O(n)
Last Updated :
02 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...