java 515.在每个树行(BFS).java中查找最大值

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 515.在每个树行(BFS).java中查找最大值相关的知识,希望对你有一定的参考价值。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> result = new ArrayList();
        if(root==null){
            return result;
        }
        result.add(root.val);
        if(root.left!=null) helper(root.left, result, 1);
        if(root.right!=null) helper(root.right, result, 1);
        return result;
    }

    void helper(TreeNode root, List<Integer> result, int level){
        if(result.size()==level){
            result.add(root.val);
        }else if(root.val > result.get(level)){
            result.set(level, root.val);
        }
        if(root.left!=null) helper(root.left, result, level+1);
        if(root.right!=null) helper(root.right, result, level+1);
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) return res;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            int curSize = queue.size();
            int max = Integer.MIN_VALUE;
            for (int i = 0; i < curSize; i++) {
                TreeNode cur = queue.poll();
                max = Math.max(max, cur.val);
                if (cur.left != null) queue.offer(cur.left);
                if (cur.right != null) queue.offer(cur.right);
            }
            res.add(max);
        }
        return res;
    }
}

以上是关于java 515.在每个树行(BFS).java中查找最大值的主要内容,如果未能解决你的问题,请参考以下文章

java 515.在每个树行(BFS).java中查找最大值

java 515.在每个树行(BFS).java中查找最大值

java 515.在每个树行(BFS).java中查找最大值

java 515.在每个树行(BFS).java中查找最大值

java 515.在每个树行(BFS).java中查找最大值

java 515.在每个树行(BFS).java中查找最大值