Largest value in each level of Binary Tree
Given a binary tree, find the largest value in each level.
Examples :
Input :
1
/ \
2 3
Output : 1 3
Input :
4
/ \
9 2
/ \ \
3 5 7
Output : 4 9 7
Approach: The idea is to recursively traverse tree in a pre-order fashion. Root is considered to be at zeroth level. While traversing, keep track of the level of the element and if its current level is not equal to the number of elements present in the list, update the maximum element at that level in the list.
Below is the implementation to find largest value on each level of Binary Tree.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int val;
struct Node *left, *right;
};
void helper(vector< int >& res, Node* root, int d)
{
if (!root)
return ;
if (d == res.size())
res.push_back(root->val);
else
res[d] = max(res[d], root->val);
helper(res, root->left, d + 1);
helper(res, root->right, d + 1);
}
vector< int > largestValues(Node* root)
{
vector< int > res;
helper(res, root, 0);
return res;
}
Node* newNode( int data)
{
Node* temp = new Node;
temp->val = data;
temp->left = temp->right = NULL;
return temp;
}
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);
vector< int > res = largestValues(root);
for ( int i = 0; i < res.size(); i++)
cout << res[i] << " " ;
return 0;
}
|
Java
import java.util.*;
public class GFG
{
static class Node
{
int val;
Node left, right;
};
static void helper(Vector<Integer> res, Node root, int d)
{
if (root == null )
return ;
if (d == res.size())
res.add(root.val);
else
res.set(d, Math.max(res.get(d), root.val));
helper(res, root.left, d + 1 );
helper(res, root.right, d + 1 );
}
static Vector<Integer> largestValues(Node root)
{
Vector<Integer> res = new Vector<>();
helper(res, root, 0 );
return res;
}
static Node newNode( int data)
{
Node temp = new Node();
temp.val = data;
temp.left = temp.right = null ;
return temp;
}
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 );
Vector<Integer> res = largestValues(root);
for ( int i = 0 ; i < res.size(); i++)
System.out.print(res.get(i)+ " " );
}
}
|
Python3
def helper(res, root, d):
if ( not root):
return
if (d = = len (res)):
res.append(root.val)
else :
res[d] = max (res[d], root.val)
helper(res, root.left, d + 1 )
helper(res, root.right, d + 1 )
def largestValues(root):
res = []
helper(res, root, 0 )
return res
class newNode:
def __init__( self , data):
self .val = data
self .left = None
self .right = None
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 )
print ( * largestValues(root))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public class Node
{
public int val;
public Node left, right;
};
static void helper(List< int > res,
Node root, int d)
{
if (root == null )
return ;
if (d == res.Count)
res.Add(root.val);
else
res[d] = Math.Max(res[d], root.val);
helper(res, root.left, d + 1);
helper(res, root.right, d + 1);
}
static List< int > largestValues(Node root)
{
List< int > res = new List< int >();
helper(res, root, 0);
return res;
}
static Node newNode( int data)
{
Node temp = new Node();
temp.val = data;
temp.left = temp.right = null ;
return temp;
}
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);
List< int > res = largestValues(root);
for ( int i = 0; i < res.Count; i++)
Console.Write(res[i] + " " );
}
}
|
Javascript
<script>
class Node
{
constructor(data) {
this .left = null ;
this .right = null ;
this .val = data;
}
}
function helper(res, root, d)
{
if (root == null )
return ;
if (d == res.length)
res.push(root.val);
else
res[d] = Math.max(res[d], root.val);
helper(res, root.left, d + 1);
helper(res, root.right, d + 1);
}
function largestValues(root)
{
let res = [];
helper(res, root, 0);
return res;
}
function newNode(data)
{
let temp = new Node(data);
return temp;
}
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);
let res = largestValues(root);
for (let i = 0; i < res.length; i++)
document.write(res[i]+ " " );
</script>
|
Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
Complexity Analysis:
- Time complexity: O(n), where n is the number of nodes in binary tree.
- Auxiliary Space: O(n) as in worst case, depth of binary tree will be n.
Another Approach:
The above approach for finding the largest value on each level of a binary tree is based on the level-order traversal technique.
Intuition:
The approach first creates an empty queue and pushes the root node into it. Then it enters into a while loop that will run until the queue is not empty. Inside the while loop, it first calculates the current size of the queue, which represents the number of nodes present at the current level. Then it loops through all the nodes at the current level and pushes their child nodes (if any) into the queue. While doing this, it also checks if the current node’s value is greater than the current maximum value for that level. If it is greater, then it updates the maximum value for that level.
After the loop, it adds the current maximum value to the result vector. Once all the levels are traversed, the result vector containing the largest value on each level is returned.
This approach has a time complexity of O(N), where N is the number of nodes in the binary tree, as it traverses each node only once. The space complexity of this approach is also O(N), as the maximum number of nodes that can be present in the queue at any given time is N/2 (the number of nodes in the last level of a complete binary tree).
Here are the implementation:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int val;
struct Node *left, *right;
};
vector< int > largestValues(Node* root) {
vector< int > res;
if (!root) return res;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int n = q.size();
int maxVal = INT_MIN;
for ( int i = 0; i < n; i++) {
Node* node = q.front();
q.pop();
maxVal = max(maxVal, node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
res.push_back(maxVal);
}
return res;
}
Node* newNode( int data)
{
Node* temp = new Node;
temp->val = data;
temp->left = temp->right = NULL;
return temp;
}
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);
vector< int > res = largestValues(root);
for ( int i = 0; i < res.size(); i++)
cout << res[i] << " " ;
return 0;
}
|
Java
import java.util.*;
class Node {
int val;
Node left, right;
Node( int data)
{
val = data;
left = right = null ;
}
}
public class GFG {
static List<Integer> largestValues(Node root)
{
List<Integer> res = new ArrayList<>();
if (root == null )
return res;
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int n = q.size();
int maxVal = Integer.MIN_VALUE;
for ( int i = 0 ; i < n; i++) {
Node node = q.poll();
maxVal = Math.max(maxVal, node.val);
if (node.left != null )
q.add(node.left);
if (node.right != null )
q.add(node.right);
}
res.add(maxVal);
}
return res;
}
public static void main(String[] args)
{
Node root = new Node( 4 );
root.left = new Node( 9 );
root.right = new Node( 2 );
root.left.left = new Node( 3 );
root.left.right = new Node( 5 );
root.right.right = new Node( 7 );
List<Integer> res = largestValues(root);
for ( int i = 0 ; i < res.size(); i++)
System.out.print(res.get(i) + " " );
}
}
|
Python
from collections import deque
class Node:
def __init__( self , val = 0 , left = None , right = None ):
self .val = val
self .left = left
self .right = right
def largestValues(root):
res = []
if not root:
return res
q = deque()
q.append(root)
while q:
n = len (q)
maxVal = float ( '-inf' )
for i in range (n):
node = q.popleft()
maxVal = max (maxVal, node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
res.append(maxVal)
return res
def newNode(data):
temp = Node()
temp.val = data
temp.left = temp.right = None
return temp
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 )
res = largestValues(root)
for val in res:
print (val),
|
C#
using System;
using System.Collections.Generic;
class Node {
public int val;
public Node left, right;
public Node( int item)
{
val = item;
left = right = null ;
}
}
class GFG {
static List< int > LargestValues(Node root)
{
List< int > res
= new List< int >();
if (root == null )
return res;
Queue<Node> q
= new Queue<Node>();
q.Enqueue(root);
while (q.Count > 0) {
int n = q.Count;
int maxVal = int .MinValue;
for ( int i = 0; i < n; i++) {
Node node
= q.Dequeue();
maxVal = Math.Max(
maxVal,
node.val);
if (node.left != null )
q.Enqueue(node.left);
if (node.right != null )
q.Enqueue(node.right);
}
res.Add(maxVal);
}
return res;
}
static void Main()
{
Node root = new Node(4);
root.left = new Node(9);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.right = new Node(7);
List< int > res = LargestValues(root);
for ( int i = 0; i < res.Count; i++)
Console.Write(res[i] + " " );
}
}
|
Javascript
class TreeNode {
constructor(val) {
this .val = val;
this .left = null ;
this .right = null ;
}
}
function largestValues(root) {
const res = [];
if (!root) return res;
const queue = [];
queue.push(root);
while (queue.length > 0) {
const n = queue.length;
let maxVal = Number.MIN_SAFE_INTEGER;
for (let i = 0; i < n; i++) {
const node = queue.shift();
maxVal = Math.max(maxVal, node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
res.push(maxVal);
}
return res;
}
function newNode(data) {
const temp = new TreeNode(data);
return temp;
}
function main() {
const 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);
const res = largestValues(root);
console.log( "Largest values on each level:" );
for (let i = 0; i < res.length; i++) {
console.log(res[i]);
}
}
main();
|
Time complexity: O(N)
Auxiliary Space: O(W)
The time complexity of the above approach is O(N), where N is the number of nodes in the binary tree. This is because the algorithm visits each node once, and each operation performed on a node takes constant time.
The space complexity of the algorithm is O(W), where W is the maximum width of the binary tree. In the worst case, the algorithm will have to store all the nodes in the last level of the binary tree in the queue before processing them. The maximum number of nodes that can be present in the last level of a binary tree is (N+1)/2, where N is the total number of nodes in the tree. Therefore, the space complexity of the algorithm is O((N+1)/2), which simplifies to O(N) in the worst case.
Approach: Using BFS
This program using a Breadth-First Search (BFS) approach finds the largest value on each level of a binary tree. Here’s the intuition behind the algorithm:
- We start by initializing an empty vector res to store the largest values on each level of the tree.
- We perform a BFS traversal of the binary tree using a queue. We start by pushing the root node into the queue.
- While the queue is not empty, we process each level of the tree: a. Get the current size of the queue. This represents the number of nodes at the current level. b. Initialize a variable levelMax to store the maximum value at the current level. Set it to the minimum possible integer value (INT_MIN). c. Iterate through all the nodes at the current level. Remove each node from the queue and update levelMax if the value of the current node is greater than levelMax. d. Enqueue the left and right child nodes of the current node (if they exist) to continue the BFS traversal of the next level. e. Once we process all the nodes at the current level, we have the maximum value for that level. Append levelMax to the res vector.
- After the BFS traversal is complete, the res vector will contain the largest value on each level of the binary tree.
- Finally, we return the res vector.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int val;
struct Node *left, *right;
};
vector< int > largestValues(Node* root)
{
vector< int > res;
if (!root)
return res;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
int levelMax = INT_MIN;
for ( int i = 0; i < size; i++) {
Node* current = q.front();
q.pop();
levelMax = max(levelMax, current->val);
if (current->left)
q.push(current->left);
if (current->right)
q.push(current->right);
}
res.push_back(levelMax);
}
return res;
}
Node* newNode( int data)
{
Node* temp = new Node;
temp->val = data;
temp->left = temp->right = NULL;
return temp;
}
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);
vector< int > res = largestValues(root);
for ( int i = 0; i < res.size(); i++)
cout << res[i] << " " ;
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode( int val) {
this .val = val;
}
}
public class Main {
public static List<Integer> largestValues(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null )
return result;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int levelSize = queue.size();
int levelMax = Integer.MIN_VALUE;
for ( int i = 0 ; i < levelSize; i++) {
TreeNode current = queue.poll();
levelMax = Math.max(levelMax, current.val);
if (current.left != null )
queue.offer(current.left);
if (current.right != null )
queue.offer(current.right);
}
result.add(levelMax);
}
return result;
}
public static void main(String[] args) {
TreeNode root = new TreeNode( 4 );
root.left = new TreeNode( 9 );
root.right = new TreeNode( 2 );
root.left.left = new TreeNode( 3 );
root.left.right = new TreeNode( 5 );
root.right.right = new TreeNode( 7 );
List<Integer> result = largestValues(root);
for ( int value : result)
System.out.print(value + " " );
}
}
|
Python
from collections import deque
class TreeNode:
def __init__( self , val = 0 , left = None , right = None ):
self .val = val
self .left = left
self .right = right
def largestValues(root):
if not root:
return []
result = []
queue = deque()
queue.append(root)
while queue:
level_size = len (queue)
level_max = float ( "-inf" )
for _ in range (level_size):
current = queue.popleft()
level_max = max (level_max, current.val)
if current.left:
queue.append(current.left)
if current.right:
queue.append(current.right)
result.append(level_max)
return result
root = TreeNode( 4 )
root.left = TreeNode( 9 )
root.right = TreeNode( 2 )
root.left.left = TreeNode( 3 )
root.left.right = TreeNode( 5 )
root.right.right = TreeNode( 7 )
result = largestValues(root)
print (result)
|
C#
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode( int val = 0, TreeNode left = null ,
TreeNode right = null )
{
this .val = val;
this .left = left;
this .right = right;
}
}
public class Solution {
public IList< int > LargestValues(TreeNode root)
{
List< int > result = new List< int >();
if (root == null )
return result;
Queue<TreeNode> queue = new Queue<TreeNode>();
queue.Enqueue(root);
while (queue.Count > 0) {
int levelMax = int .MinValue;
int levelSize = queue.Count;
for ( int i = 0; i < levelSize; i++) {
TreeNode current = queue.Dequeue();
levelMax = Math.Max(levelMax, current.val);
if (current.left != null )
queue.Enqueue(current.left);
if (current.right != null )
queue.Enqueue(current.right);
}
result.Add(levelMax);
}
return result;
}
}
class Program {
static void Main( string [] args)
{
TreeNode root = new TreeNode(4);
root.left = new TreeNode(9);
root.right = new TreeNode(2);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(7);
Solution solution = new Solution();
IList< int > result = solution.LargestValues(root);
Console.WriteLine( "Largest values at each level:" );
foreach ( int val in result)
{
Console.Write(val + " " );
}
}
}
|
Javascript
class TreeNode {
constructor(val) {
this .val = val;
this .left = this .right = null ;
}
}
function largestValues(root) {
const res = [];
if (!root) {
return res;
}
const queue = [root];
while (queue.length > 0) {
const size = queue.length;
let levelMax = -Infinity;
for (let i = 0; i < size; i++) {
const current = queue.shift();
levelMax = Math.max(levelMax, current.val);
if (current.left) {
queue.push(current.left);
}
if (current.right) {
queue.push(current.right);
}
}
res.push(levelMax);
}
return res;
}
const root = new TreeNode(4);
root.left = new TreeNode(9);
root.right = new TreeNode(2);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(7);
const res = largestValues(root);
console.log(res.join( " " ));
|
Time complexity: O(N), where N is the number of nodes in the binary tree, as we need to visit each node once.
Auxiliary Space: O(M), where M is the maximum number of nodes at any level in the tree, as the queue can store at most M nodes at a time during the BFS traversal.
Last Updated :
12 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...