Algorithm


Problem Name: 515. Find Largest Value in Each Tree Row

Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).

 

Example 1:

Input: root = [1,3,2,5,3,null,9]
Output: [1,3,9]

Example 2:

Input: root = [1,2,3]
Output: [1,3]

 

Constraints:

  • The number of nodes in the tree will be in the range [0, 104].
  • -231 <= Node.val <= 231 - 1

Code Examples

#1 Code Example with C++ Programming

Code - C++ Programming


// BFS
class Solution {
public:
    vector<int> largestValues(TreeNode* root) {
        if(!root) return {};
        vector<int>res;
        deque < TreeNode*>cur, next;
        cur.push_back(root);
        int val = INT_MIN;
        while(!cur.empty()){
            auto p = cur.front();
            cur.pop_front();
            if(p->left) next.push_back(p->left);
            if(p->right) next.push_back(p->right);
            val = max(val, p->val);
            if(cur.empty()){
                swap(cur, next);
                res.push_back(val);
                val = INT_MIN;
            }
        }
        return res;
    }
};

// DFS
class Solution {
public:
    vector<int> largestValues(TreeNode* root) {
        vector<int>res;
        DFS(root, res, 0);
        return res;
    }
    
    void DFS(TreeNode* root, vector<int>& res, int level){
        if(!root) return;
        if(res.size() == level) res.push_back(root->val);
        res[level] = max(res[level], root->val);
        DFS(root->left, res, level + 1);
        DFS(root->right, res, level + 1);
    }
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
root = [1,3,2,5,3,null,9]

Output

x
+
cmd
[1,3,9]

#2 Code Example with Java Programming

Code - Java Programming


class Solution {
  public List largestValues(TreeNode root) {
    List list = new ArrayList<>();
    if (root == null) {
      return list;
    }
    Queue < TreeNode> queue = new LinkedList<>();
    queue.add(root);
    while (!queue.isEmpty()) {
      int maxVal = Integer.MIN_VALUE;
      int size = queue.size();
      while (size-- > 0) {
        TreeNode removed = queue.remove();
        maxVal = Math.max(maxVal, removed.val);
        if (removed.left != null) {
          queue.add(removed.left);
        }
        if (removed.right != null) {
          queue.add(removed.right);
        }
      }
      list.add(maxVal);
    }
    return list;
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
root = [1,3,2,5,3,null,9]

Output

x
+
cmd
[1,3,9]

#3 Code Example with Javascript Programming

Code - Javascript Programming


const largestValues = function(root) {
  const res = [];
  single(root, 0, res);
  return res;
};

function single(node, row, arr) {
  if (node == null) {
    return null;
  }
  if (row  <  arr.length) {
    if (node.val > arr[row]) {
      arr[row] = node.val;
    }
  } else {
    arr[row] = node.val;
  }
  single(node.left, row + 1, arr);
  single(node.right, row + 1, arr);
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
root = [1,2,3]

Output

x
+
cmd
[1,3]

#4 Code Example with Python Programming

Code - Python Programming


class Solution:
    def largestValues(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        from collections import deque
        q, res, target = deque([root]) if root else None, [root.val] if root else [], root
        while q:
            node = q.popleft()
            if node.left: q.append(node.left)
            if node.right: q.append(node.right)
            if node == target and q: 
                res.append(max([i.val for i in q]))
                target = q[-1]
        return res
Copy The Code & Try With Live Editor

Input

x
+
cmd
root = [1,2,3]

Output

x
+
cmd
[1,3]

#5 Code Example with C# Programming

Code - C# Programming


using System;
using System.Collections.Generic;

namespace LeetCode
{
    /**
     * 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 _0515_FindLargestValueInEachTreeRow
    {
        public IList < int> LargestValues(TreeNode root)
        {
            if (root == null) return new List<int>();
            var queue = new Queue();
            queue.Enqueue(root);

            var result = new List < int>();
            while (queue.Count > 0)
            {
                var size = queue.Count;
                var max = int.MinValue;
                for (int i = 0; i  <  size; i++)
                {
                    var node = queue.Dequeue();
                    max = Math.Max(max, node.val);
                    if (node.left != null) queue.Enqueue(node.left);
                    if (node.right != null) queue.Enqueue(node.right);
                }

                result.Add(max);
            }

            return result;
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
root = [1,3,2,5,3,null,9]

Output

x
+
cmd
[1,3,9]
Advertisements

Demonstration


Previous
#514 Leetcode Freedom Trail Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#516 Leetcode Longest Palindromic Subsequence Solution in C, C++, Java, JavaScript, Python, C# Leetcode