515. Find Largest Value in Each Tree Row

Posted wentiliangkaihua

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了515. 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]

class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> res = new ArrayList();
        List<List<Integer>> help = levelOrder(root);
        for(List<Integer> list : help) res.add(Collections.max(list));
        return res;
    }
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        Helper(0, root, res);
        return res;
    }
    public void Helper(int height, TreeNode p, List<List<Integer>> res){
        if(p == null) return;
        if(height == res.size()){
            res.add(new ArrayList());
        }
        res.get(height).add(p.val);
        Helper(height + 1, p.left, res);
        Helper(height + 1, p.right, res);
    }
}

先level order,再把每层最大的拉出来。

public class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        helper(root, res, 0);
        return res;
    }
    private void helper(TreeNode root, List<Integer> res, int d){
        if(root == null){
            return;
        }
       //expand list size
        if(d == res.size()){
            res.add(root.val);
        }
        else{
        //or set value
            res.set(d, Math.max(res.get(d), root.val));
        }
        helper(root.left, res, d+1);
        helper(root.right, res, d+1);
    }
}

或者直接用d记录层数,每遍历到一个就更新一次。

以上是关于515. Find Largest Value in Each Tree Row的主要内容,如果未能解决你的问题,请参考以下文章

515. Find Largest Value in Each Tree Row

515. Find Largest Value in Each Tree Row

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

[LeetCode]515 Find Largest Value in Each Tree Row(dfs)

[leetcode-515-Find Largest Value in Each Tree Row]

(BFS 二叉树) leetcode 515. Find Largest Value in Each Tree Row