C/C++教程

515. Find Largest Value in Each Tree Row

本文主要是介绍515. Find Largest Value in Each Tree Row,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

My BFS solution:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
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 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.offer(node.left);
                if(node.right!=null)
                    queue.offer(node.right);
            }
            res.add(max);
        }
        return res;
    }
}

 

这篇关于515. Find Largest Value in Each Tree Row的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!