Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Largest BST in a Binary Tree
Next article icon

Largest value in each level of Binary Tree

Last Updated : 22 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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
Maximum Value
Solve 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 <bits/stdc++.h> 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<Integer> 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<Integer> largestValues(Node root)  {      Vector<Integer> 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<Integer> res = largestValues(root);      for (int i = 0; i < res.size(); i++)              System.out.print(res.get(i)+" "); } }  /* This code is contributed by PrinciRaj1992 */ 
Python
# 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
    // JavaScript program to find largest      // value on each level of binary tree.      /* A binary tree node has data,      pointer to left child and a      pointer to right child */     class Node     {         constructor(data) {            this.left = null;            this.right = null;            this.val = data;         }     }          /* Recursive function to find      the largest value on each level */     function helper(res, root, d)      {          if (root == null)              return;           // Expand list size          if (d == res.length)              res.push(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      function largestValues(root)      {          let res = [];          helper(res, root, 0);          return res;      }       /* Helper function that allocates a      new node with the given data and      NULL left and right pointers. */     function newNode(data)      {          let temp = new Node(data);          return temp;      }           /* Let us construct a Binary Tree          4      / \      9 2      / \ \      3 5 7 */        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++)              console.log(res[i]+" ");      

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 are the implementation:

C++
#include <bits/stdc++.h> 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<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; }  /* 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
import java.util.*;  // A binary tree node has data, // pointer to left child, and a // pointer to the right child class Node {     int val;     Node left, right;      Node(int data)     {         val = data;         left = right = null;     } }  public class GFG {      // Function to find largest value on each level of     // binary tree     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;     }      // Driver code     public static void main(String[] args)     {         /* Let us construct a Binary Tree                     4                    / \                   9   2                  / \   \                 3   5   7 */          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  # A binary tree node has data, pointer to left child,  # and a pointer to right child   class Node:     def __init__(self, val=0, left=None, right=None):         self.val = val         self.left = left         self.right = right  # Function to find the largest value on each level of a binary tree   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  # Helper function that allocates a new node with the given data and NULL left and right pointers   def newNode(data):     temp = Node()     temp.val = data     temp.left = temp.right = None     return temp   # Driver code if __name__ == "__main__":     # Let us construct a Binary 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)      res = largestValues(root)     for val in res:         print(val), 
C#
using System; using System.Collections.Generic;  /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node {     public int val;     public Node left, right;      public Node(int item)     {         val = item;         left = right = null;     } }  class GFG {     // Function to find the largest values in each level of     // a binary tree     static List<int> LargestValues(Node root)     {         List<int> res             = new List<int>(); // Initialize a list to store                                // the largest values         if (root == null)             return res; // Return an empty list if the tree                         // is empty          Queue<Node> q             = new Queue<Node>(); // Create a queue to                                  // perform a level-order                                  // traversal         q.Enqueue(root); // Enqueue the root node as the                          // starting point          // Perform a level-order traversal of the binary         // tree         while (q.Count > 0) {             int n = q.Count; // Get the number of nodes at                              // the current level             int maxVal = int.MinValue; // Initialize the                                        // maximum value for                                        // the current level              // Traverse all the nodes at the current level             for (int i = 0; i < n; i++) {                 Node node                     = q.Dequeue(); // Dequeue the front node                 maxVal = Math.Max(                     maxVal,                     node.val); // Update the maximum value                                // for the current level                  // Enqueue the left and right child nodes of                 // the current node if they exist                 if (node.left != null)                     q.Enqueue(node.left);                 if (node.right != null)                     q.Enqueue(node.right);             }              // After traversing all nodes at the current             // level, add the maximum value to the result             // list             res.Add(maxVal);         }          return res; // Return the list containing the                     // largest values at each level of the                     // binary tree     }      static void Main()     {         // Construct the binary tree         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);          // Find the largest values at each level and print         // the results         List<int> res = LargestValues(root);         for (int i = 0; i < res.Count; i++)             Console.Write(res[i] + " ");     } } 
JavaScript
// Definition of a binary tree node class TreeNode {     constructor(val) {         this.val = val;         this.left = null;         this.right = null;     } }  // Function to find the largest value on each level of a binary tree 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; }  // Helper function to construct a new tree node function newNode(data) {     const temp = new TreeNode(data);     return temp; }  // Driver code function main() {     // Construct the binary tree:     //       4     //      / \     //     9   2     //    / \   \     //   3   5   7      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]);     } }  // Call the main function to start the program main(); 

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 <bits/stdc++.h> 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<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; }  /* 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
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 {     // Function to find the largest values in each level of a binary tree     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;              // Iterate through nodes at the current level             for (int i = 0; i < levelSize; i++) {                 TreeNode current = queue.poll();                 levelMax = Math.max(levelMax, current.val);                  // Add child nodes to the queue if they exist                 if (current.left != null)                     queue.offer(current.left);                 if (current.right != null)                     queue.offer(current.right);             }              // Add the maximum value of the current level to the result list             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);          // Find the largest values in each level of the binary tree         List<Integer> result = largestValues(root);          // Print the result         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 = []  # Initialize a list to store the largest values on each level     queue = deque()  # Create a queue for BFS traversal, starting with the root node     queue.append(root)      while queue:         level_size = len(queue)         # Initialize the maximum value for the current level         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)          # Append the maximum value for the current level to the result list         result.append(level_max)      return result   # Input: Construct the binary tree #        4 #       / \ #      9   2 #     / \   \ #    3   5   7 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)  # Find the largest values on each level result = largestValues(root) print(result)  # Output: [4, 9, 7] 
C#
using System; using System.Collections.Generic; using System.Collections; using System.Linq;  // Definition for a binary tree node 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)     {         /* Let us construct a Binary Tree            4           / \          9   2         / \   \        3   5   7 */          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
// Definition for a binary tree node. 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; }  // Driver code 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(" ")); 

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.     



Next Article
Largest BST in a Binary Tree

P

Pal13
Improve
Article Tags :
  • DSA
  • Tree
  • tree-level-order
Practice Tags :
  • Tree

Similar Reads

  • Smallest value in each level of Binary Tree
    Given a binary tree containing n nodes, the task is to print the minimum elements in each level of the binary tree. Examples: Input : 7 / \ 6 5 / \ / \ 4 3 2 1 Output : Every level minimum is level 0 min is = 7 level 1 min is = 5 level 2 min is = 1 Input : 7 / \ 16 1 / \ 4 13 Output : Every level mi
    15+ min read
  • 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 me
    9 min read
  • Maximum value at each level in an N-ary Tree
    Given a N-ary Tree consisting of nodes valued in the range [0, N - 1] and an array arr[] where each node i is associated to value arr[i], the task is to print the maximum value associated with any node at each level of the given N-ary Tree. Examples: Input: N = 8, Edges[][] = {{0, 1}, {0, 2}, {0, 3}
    9 min read
  • Largest BST in a Binary Tree
    Given a Binary Tree, the task is to return the size of the largest subtree which is also a Binary Search Tree (BST). If the complete Binary Tree is BST, then return the size of the whole tree. Examples: Input: Output: 3 Explanation: The below subtree is the maximum size BST: Input: Output: 3 Explana
    14 min read
  • Maximum number in Binary tree of binary values
    Given a binary tree consisting of nodes, each containing a binary value of either 0 or 1, the task is to find the maximum decimal number that can be formed by traversing from the root to a leaf node. The maximum number is achieved by concatenating the binary values along the path from the root to a
    6 min read
  • Largest number possible by arranging node values at each level
    Given a Binary Tree with positive values at each node, the task is to print the maximum number that can be formed by arranging nodes at each level. Examples: Input: 4 / \ 2 59 / \ / \ 1 3 2 6Output: Maximum number at 0'th level is 4Maximum number at 1'st level is 592Maximum number at 2'nd level is 6
    10 min read
  • Find all duplicate levels of given Binary Tree
    A binary tree is a tree data structure in which each node has at most two child nodes, referred to as the left and right children. In this question, the task is to find all the duplicate levels of a given binary tree. This problem can be used to identify and resolve any duplicate nodes or values in
    13 min read
  • Level of a Node in Binary Tree
    Given a Binary Tree and a key, the task is to find the level of key in the Binary Tree. Examples: Input : key = 4 Output: 3Explanation: The level of the key in above binary tree is 3.Input : key = 10 Output: -1Explanation: Key is not present in the above Binary tree. Table of Content [Expected Appro
    12 min read
  • Largest element in an N-ary Tree
    Given an n-ary tree containing positive node values, the task is to find the node with the largest value in the given n-ary tree.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), the n-a
    5 min read
  • Second Largest element in n-ary tree
    Given an n-ary tree containing positive node values, the task is to find the node with the second largest value in the given n-ary tree. If there is no second largest node return -1.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences