515-Find Largest Value in Each Tree Row

kevin聰發表於2018-05-03

Description

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]

問題描述

找出二叉樹每層中最大的值


問題分析

前序遍歷, 注意利用高度


解法1

class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> res = new ArrayList();
        if (root == null) return res;

        Queue<TreeNode> queue = new LinkedList();
        queue.add(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            int max = Integer.MIN_VALUE;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                max = Math.max(max, node.val);
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
            res.add(max);
        }

        return res;
    }
}

解法2

class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> res = new ArrayList();
        if(root == null) return res;

        find(root, res, 0);

        return res;
    }
    public void find(TreeNode root, List<Integer> res, int depth){
        if(root == null) return;

        if(depth >= res.size()) res.add(root.val);
        else if(res.get(depth) < root.val) res.set(depth, root.val);
        find(root.left, res, depth + 1);
        find(root.right, res, depth + 1);
    }
}

相關文章