GFG App
Open App
Browser
Continue

# 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```
Recommended Problem

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

 `// 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.*;`   ` ``public` `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`

## Javascript

 ``

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.

### 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 is the implementation in C++:

## C++

 `#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;` `};`   `/* Function to find largest value` `on each level of binary tree */` `vector<``int``> largestValues(Node* root) {` `    ``vector<``int``> res;` `    ``if` `(!root) ``return` `res;` `    ``queue 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;` `}`   `/* 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;` `}`

Output

`4 9 7 `

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:

1. We start by initializing an empty vector res to store the largest values on each level of the tree.
2. We perform a BFS traversal of the binary tree using a queue. We start by pushing the root node into the queue.
3. 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.
4. After the BFS traversal is complete, the res vector will contain the largest value on each level of the binary tree.
5. Finally, we return the res vector.

## C++

 `#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;` `};`   `// function to find largest values` `vector<``int``> largestValues(Node* root)` `{` `    ``vector<``int``> res;` `    ``if` `(!root)` `        ``return` `res;`   `    ``queue 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;` `}`   `/* 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;` `}`

Output

`4 9 7 `

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.

My Personal Notes arrow_drop_up