Open In App

Largest value in each level of Binary Tree

Improve
Improve
Like Article
Like
Save
Share
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

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 */


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




<script>
 
    // 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++)
            document.write(res[i]+" ");
     
</script>


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.     



Last Updated : 12 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads