2018-08-14 LeetCode在每个树行中找最大值

class Solution {
    public List<Integer> largestValues(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
         List<Integer> ans = new LinkedList<>();
         if (root == null) {
            return ans;
        }
        queue.offer(root);
        TreeNode last = root;
        TreeNode nLast = null;
        int max = Integer.MIN_VALUE;
        while (!queue.isEmpty()) {
            root = queue.poll();
            max = root.val > max ? root.val : max;
            if (root.left != null) {
                queue.offer(root.left);
                nLast = root.left;
            }
            if (root.right != null) {
                queue.offer(root.right);
                nLast = root.right;
            }
            if (root == last && !queue.isEmpty()) {
                ans.add(max);
                max = Integer.MIN_VALUE;
                last = nLast;
            }
        }
        ans.add(max);
        return ans;
    }
}
class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if (root == null) return res;
        queue.add(root);
        while (!queue.isEmpty()) {
            int max = Integer.MIN_VALUE;
            int size = queue.size();
            for ( int i = 0; i < size; i++) {
                TreeNode node = queue.remove();
                if (node.val > 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;
    }
}
class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> list=new ArrayList<>();
        check(root,0,list);
        return list;
    }

    public void check(TreeNode node,int index,List<Integer> list){
        if(node==null){
            return;
        }
        if(index >= list.size()){
            list.add(node.val);
        }else {
            list.set(index,Math.max(node.val,list.get(index)));
        }
        check(node.left,index+1,list);
        check(node.right,index+1,list);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 今天又迎來了一批高級班死黨結業啦!每一期高級班的結業都帶給我們許多感動,這份感動是我們每個人作為生命個體,對...
    精尚阅读 1,346评论 0 0
  • 刚接到朋友一个电话,说明天下午踢球,问好了具体时间地点后,我很诚恳的感谢到“明天下午一定来,不来就请你吃饭”(我已...
    迎刃阅读 3,177评论 0 2
  • 1>用纸和笔将最初的想法先构思一下。 2>用Axure做最粗略的原型,把主要信息结构与操作过程表达出来。 3>用A...
    Jessica流年阅读 3,863评论 0 8
  • 1 新生报到的第一天,小花早早地来到学校,与小学相比,这里真大也很美。小花双手扯着书包带,认真地观看学校的每一个角...
    一盏灯ll阅读 2,472评论 0 1

友情链接更多精彩内容