515.Find-Largest-Value-in-Each-Tree-Row

515. Find Largest Value in Each Tree Row

题目地址

https://leetcode.com/problems/find-largest-value-in-each-tree-row/

题目描述

You need to find the largest value in each row of a binary tree.

Example:
Input: 

          1
         / \
        3   2
       / \   \  
      5   3   9 

Output: [1, 3, 9]

代码

Approach #1 DFS with depth

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
  public List<Integer> largestValues(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
    dfs(root, res, 0);
    return res;
  }

  private void dfs(TreeNode root, List<Integer> res, int d) {
    if (root == null)    return;
    if (d == res.size()) {
      res.add(root.val);
    } else {
      res.set(d, Math.max(res.get(d), root.val));
    }
    dfs(root.left, res, d + 1);
    dfs(root.right, res, d + 1);
  }
}

Approach #2 BFS

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> largestValues(TreeNode root) {
      Queue<TreeNode> queue = new LinkedList<TreeNode>();
      List<Integer> res = new ArrayList();
      if (root == null)   return res;
      queue.add(root);
      int queueSize = root == null ? 0 : 1;
      while (queueSize > 0) {
        int largestElement = Integer.MIN_VALUE;
        for (int i = 0; i < queueSize; i++) {
          TreeNode node = queue.poll();
          largestElement = Math.max(node.val, largestElement);
          if (node.left != null) queue.add(node.left);
          if (node.right != null) queue.add(node.right);
        }
        res.add(largestElement);
        queueSize = queue.size();
      }

    return res;
  } 
}

Last updated