zoukankan      html  css  js  c++  java
  • 剑指 Offer 32

    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> result=new ArrayList<>();//这里注意
            if(root==null)
            {return result;}
            Queue<TreeNode> queue=new LinkedList<>();
            queue.add(root);
            while(queue.size()!=0)
            {
                List<Integer> listLevel=new ArrayList<>();
                int count=queue.size();
                for(int i=0;i<count;i++)
                {
                    TreeNode node=queue.poll();
                    listLevel.add(node.val);
                    if(node.left!=null)
                    {queue.add(node.left);}
                    if(node.right!=null)
                    {queue.add(node.right);}
                }
                result.add(listLevel);
            }
            return result;
    
        }
    }

    这题之前做过,思路也都有了,但仍然在做的过程中发现了一些问题:

    1. List<List<Integer>>的new
    2. 空树问题
    3. 用错了for(int i=0;i<queue.size();i++)

    1.List<List<Integer>>的new

    一开始写成了

    List<List<Integer>> result=new ArrayList<ArrayList<Integer>>();

    泛型问题,应该写成:

    List<List<Integer>> result= new ArrayList<List<Integer>>();
    //或者
    List<List<Integer>> result=new ArrayList<>();

    2.空树问题

    老问题了,不知道这次为什么没注意到

    3.for循环

    傻了,一开始写成了for(int i=0;i<queue.size();i++)

    但其实i<queue.size()一直在变,要注意这种for循环中变量的问题

  • 相关阅读:
    吃推荐3个最近去了的好地方
    30岁生日
    今天开始试用Briglow Hair Cream
    WPF中如何在文本外面加虚线外框
    对账算法改进
    如何退出正在Sleep的线程
    关于framework4.5的相关介绍
    恐怖的报警邮件
    对帐引擎2个月后的监控数据
    wcf rest服务启用gzip压缩
  • 原文地址:https://www.cnblogs.com/take-it-easy/p/14282933.html
Copyright © 2011-2022 走看看