Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
Given a binary tree containing n nodes. The problem is to find and print the largest value present in each level.
Examples:
Input :
1
/ \
2 3
Output : 1 3
Input :
4
/ \
9 2
/ \ \
3 5 7
Output : 4 9 7
Approach: In the previous post, a recursive method have been discussed. In this post an iterative method has been discussed. The idea is to perform iterative level order traversal of the binary tree using queue. While traversing keep max variable which stores the maximum element of the current level of the tree being processed. When the level is completely traversed, print that max value.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
};
Node* newNode( int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
void largestValueInEachLevel(Node* root)
{
if (!root)
return ;
queue<Node*> q;
int nc, max;
q.push(root);
while (1) {
nc = q.size();
if (nc == 0)
break ;
max = INT_MIN;
while (nc--) {
Node* front = q.front();
q.pop();
if (max < front->data)
max = front->data;
if (front->left)
q.push(front->left);
if (front->right)
q.push(front->right);
}
cout << max << " " ;
}
}
int main()
{
Node* root = NULL;
root = newNode(4);
root->left = newNode(9);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(5);
root->right->right = newNode(7);
largestValueInEachLevel(root);
return 0;
}
|
Java
import java.util.*;
class GfG {
static class Node
{
int data;
Node left = null ;
Node right = null ;
}
static Node newNode( int val)
{
Node temp = new Node();
temp.data = val;
temp.left = null ;
temp.right = null ;
return temp;
}
static void largestValueInEachLevel(Node root)
{
if (root == null )
return ;
Queue<Node> q = new LinkedList<Node>();
int nc, max;
q.add(root);
while ( true )
{
nc = q.size();
if (nc == 0 )
break ;
max = Integer.MIN_VALUE;
while (nc != 0 )
{
Node front = q.peek();
q.remove();
if (max < front.data)
max = front.data;
if (front.left != null )
q.add(front.left);
if (front.right != null )
q.add(front.right);
nc--;
}
System.out.println(max + " " );
}
}
public static void main(String[] args)
{
Node root = null ;
root = newNode( 4 );
root.left = newNode( 9 );
root.right = newNode( 2 );
root.left.left = newNode( 3 );
root.left.right = newNode( 5 );
root.right.right = newNode( 7 );
largestValueInEachLevel(root);
}
}
|
Python3
INT_MIN = - 2147483648
class newNode:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def largestValueInEachLevel(root):
if ( not root):
return
q = []
nc = 10
max = 0
q.append(root)
while ( 1 ):
nc = len (q)
if (nc = = 0 ):
break
max = INT_MIN
while (nc):
front = q[ 0 ]
q = q[ 1 :]
if ( max < front.data):
max = front.data
if (front.left):
q.append(front.left)
if (front.right ! = None ):
q.append(front.right)
nc - = 1
print ( max , end = " " )
if __name__ = = '__main__' :
root = newNode( 4 )
root.left = newNode( 9 )
root.right = newNode( 2 )
root.left.left = newNode( 3 )
root.left.right = newNode( 5 )
root.right.right = newNode( 7 )
largestValueInEachLevel(root)
|
C#
using System;
using System.Collections.Generic;
class GfG
{
class Node
{
public int data;
public Node left = null ;
public Node right = null ;
}
static Node newNode( int val)
{
Node temp = new Node();
temp.data = val;
temp.left = null ;
temp.right = null ;
return temp;
}
static void largestValueInEachLevel(Node root)
{
if (root == null )
return ;
Queue<Node> q = new Queue<Node>();
int nc, max;
q.Enqueue(root);
while ( true )
{
nc = q.Count;
if (nc == 0)
break ;
max = int .MinValue;
while (nc != 0)
{
Node front = q.Peek();
q.Dequeue();
if (max < front.data)
max = front.data;
if (front.left != null )
q.Enqueue(front.left);
if (front.right != null )
q.Enqueue(front.right);
nc--;
}
Console.Write(max + " " );
}
}
public static void Main(String[] args)
{
Node root = null ;
root = newNode(4);
root.left = newNode(9);
root.right = newNode(2);
root.left.left = newNode(3);
root.left.right = newNode(5);
root.right.right = newNode(7);
largestValueInEachLevel(root);
}
}
|
Javascript
<script>
class Node
{
constructor(data) {
this .left = null ;
this .right = null ;
this .data = data;
}
}
function newNode(val)
{
let temp = new Node(val);
return temp;
}
function largestValueInEachLevel(root)
{
if (root == null )
return ;
let q = [];
let nc, max;
q.push(root);
while ( true )
{
nc = q.length;
if (nc == 0)
break ;
max = Number.MIN_VALUE;
while (nc != 0)
{
let front = q[0];
q.shift();
if (max < front.data)
max = front.data;
if (front.left != null )
q.push(front.left);
if (front.right != null )
q.push(front.right);
nc--;
}
document.write(max + " " );
}
}
let root = null ;
root = newNode(4);
root.left = newNode(9);
root.right = newNode(2);
root.left.left = newNode(3);
root.left.right = newNode(5);
root.right.right = newNode(7);
largestValueInEachLevel(root);
</script>
|
Complexity Analysis:
- Time Complexity: O(N) where N is the total number of nodes in the tree.
In level order traversal, every node of the tree is processed once and hence the complexity due to the level order traversal is O(N) if there are total N nodes in the tree. Also, while processing every node, we are maintaining the maximum element at each level, however, this does not affect the overall time complexity. Therefore, the time complexity is O(N).
- Auxiliary Space: O(w) where w is the maximum width of the tree.
In level order traversal, a queue is maintained whose maximum size at any moment can go upto the maximum width of the binary tree.
Last Updated :
02 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...