Related Articles
Largest value in each level of Binary Tree
• Difficulty Level : Medium
• Last Updated : 03 Nov, 2020

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
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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.

## C++

 `// C++ program to find largest``// value on each level of binary tree.``#include ``using` `namespace` `std;`` ` `/* A binary tree node has data,``pointer to left child and a ``pointer to right child */``struct` `Node {``    ``int` `val;``    ``struct` `Node *left, *right;``};`` ` `/* Recursive function to find``the largest value on each level */``void` `helper(vector<``int``>& res, Node* root, ``int` `d)``{``    ``if` `(!root)``        ``return``;`` ` `    ``// Expand list size``    ``if` `(d == res.size())``        ``res.push_back(root->val);`` ` `    ``else`` ` `        ``// to ensure largest value ``        ``// on level is being stored``        ``res[d] = max(res[d], root->val);`` ` `    ``// Recursively traverse left and``    ``// right subtrees in order to find``    ``// out the largest value on each level``    ``helper(res, root->left, d + 1);``    ``helper(res, root->right, d + 1);``}`` ` `// function to find largest values``vector<``int``> largestValues(Node* root)``{``    ``vector<``int``> res;``    ``helper(res, root, 0);``    ``return` `res;``}`` ` `/* Helper function that allocates a``new node with the given data and``NULL left and right pointers. */``Node* newNode(``int` `data)``{``    ``Node* temp = ``new` `Node;``    ``temp->val = data;``    ``temp->left = temp->right = NULL;``    ``return` `temp;``}`` ` `// Driver code``int` `main()``{``    ``/* Let us construct a Binary Tree``        ``4``       ``/ \``      ``9   2``     ``/ \   \``    ``3   5   7 */`` ` `    ``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

 `// Java program to find largest ``// value on each level of binary tree.``import` `java.util.*;`` ` `class` `GFG ``{`` ` `/* A binary tree node has data, ``pointer to left child and a ``pointer to right child */``static` `class` `Node ``{ ``    ``int` `val; ``    ``Node left, right; ``}; `` ` `/* Recursive function to find ``the largest value on each level */``static` `void` `helper(Vector res, Node root, ``int` `d) ``{ ``    ``if` `(root == ``null``) ``        ``return``; `` ` `    ``// Expand list size ``    ``if` `(d == res.size()) ``        ``res.add(root.val); `` ` `    ``else`` ` `        ``// to ensure largest value ``        ``// on level is being stored ``        ``res.set(d, Math.max(res.get(d), root.val)); `` ` `    ``// Recursively traverse left and ``    ``// right subtrees in order to find ``    ``// out the largest value on each level ``    ``helper(res, root.left, d + ``1``); ``    ``helper(res, root.right, d + ``1``); ``} `` ` `// function to find largest values ``static` `Vector largestValues(Node root) ``{ ``    ``Vector res = ``new` `Vector<>(); ``    ``helper(res, root, ``0``); ``    ``return` `res; ``} `` ` `/* Helper function that allocates a ``new node with the given data and ``NULL left and right pointers. */``static` `Node newNode(``int` `data) ``{ ``    ``Node temp = ``new` `Node(); ``    ``temp.val = data; ``    ``temp.left = temp.right = ``null``; ``    ``return` `temp; ``} `` ` `// Driver code ``public` `static` `void` `main(String[] args) ``{``    ``/* Let us construct a Binary Tree ``        ``4 ``    ``/ \ ``    ``9 2 ``    ``/ \ \ ``    ``3 5 7 */`` ` `    ``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 res = largestValues(root); ``    ``for` `(``int` `i = ``0``; i < res.size(); i++) ``            ``System.out.print(res.get(i)+``" "``);``}``}`` ` `/* This code is contributed by PrinciRaj1992 */`

## Python3

 `# Python program to find largest value``# on each level of binary tree.`` ` `""" Recursive function to find ``the largest value on each level """``def` `helper(res, root, d): `` ` `    ``if` `( ``not` `root): ``        ``return`` ` `    ``# Expand list size ``    ``if` `(d ``=``=` `len``(res)): ``        ``res.append(root.val) `` ` `    ``else``:`` ` `        ``# to ensure largest value ``        ``# on level is being stored ``        ``res[d] ``=` `max``(res[d], root.val) `` ` `    ``# Recursively traverse left and ``    ``# right subtrees in order to find ``    ``# out the largest value on each level ``    ``helper(res, root.left, d ``+` `1``) ``    ``helper(res, root.right, d ``+` `1``) `` ` ` ` `# function to find largest values ``def` `largestValues(root): `` ` `    ``res ``=` `[] ``    ``helper(res, root, ``0``) ``    ``return` `res`` ` ` ` `# Helper function that allocates a new ``# node with the given data and None left ``# and right pointers.                                     ``class` `newNode: `` ` `    ``# Constructor to create a new node ``    ``def` `__init__(``self``, data): ``        ``self``.val ``=` `data ``        ``self``.left ``=` `None``        ``self``.right ``=` `None`` ` `         ` `# Driver Code ``if` `__name__ ``=``=` `'__main__'``:``    ``""" Let us construct the following Tree``        ``4 ``        ``/ \ ``        ``9 2 ``    ``/ \ \``    ``3 5 7 """``    ``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))                         `` ` `# This code is contributed``# Shubham Singh(SHUBHAMSINGH10)`

## C#

 `// C# program to find largest ``// value on each level of binary tree.``using` `System;``using` `System.Collections.Generic;`` ` `class` `GFG ``{`` ` `/* A binary tree node has data, ``pointer to left child and a ``pointer to right child */``public` `class` `Node ``{ ``    ``public` `int` `val; ``    ``public` `Node left, right; ``}; `` ` `/* Recursive function to find ``the largest value on each level */``static` `void` `helper(List<``int``> res, ``                   ``Node root, ``int` `d) ``{ ``    ``if` `(root == ``null``) ``        ``return``; `` ` `    ``// Expand list size ``    ``if` `(d == res.Count) ``        ``res.Add(root.val); `` ` `    ``else`` ` `        ``// to ensure largest value ``        ``// on level is being stored ``        ``res[d] = Math.Max(res[d], root.val); `` ` `    ``// Recursively traverse left and ``    ``// right subtrees in order to find ``    ``// out the largest value on each level ``    ``helper(res, root.left, d + 1); ``    ``helper(res, root.right, d + 1); ``} `` ` `// function to find largest values ``static` `List<``int``> largestValues(Node root) ``{ ``    ``List<``int``> res = ``new` `List<``int``>(); ``    ``helper(res, root, 0); ``    ``return` `res; ``} `` ` `/* Helper function that allocates a ``new node with the given data and ``NULL left and right pointers. */``static` `Node newNode(``int` `data) ``{ ``    ``Node temp = ``new` `Node(); ``    ``temp.val = data; ``    ``temp.left = temp.right = ``null``; ``    ``return` `temp; ``} `` ` `// Driver code ``public` `static` `void` `Main(String[] args) ``{``     ` `    ``/* Let us construct a Binary Tree ``        ``4 ``    ``/ \ ``    ``9 2 ``    ``/ \ \ ``    ``3 5 7 */``    ``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] + ``" "``);``}``}`` ` `// This code is contributed by 29AjayKumar`

Output:

```4 9 7
```

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.

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.

My Personal Notes arrow_drop_up