二叉树的层次遍历

此博客链接:

层次遍历

题目链接:https://leetcode-cn.com/leetbook/read/data-structure-binary-tree/xefh1i/

题目

给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。

示例:
二叉树:[3,9,20,null,null,15,7],

3
/
9 20
/
15 7
返回其层序遍历结果:

[
[3],
[9,20],
[15,7]
]

题解

使用队列,在每次的节点放入队列,然后把队列中每取出一个节点,把孩子节点也放入到队列中,直到每层节点访问完,重复操作,直到节点全部出队列,遍历的结果就是层次遍历。

代码

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
       Queue<TreeNode> que= new LinkedList<TreeNode>();
       
        List<List<Integer>> res =new ArrayList();
       que.offer(root);
       while(!que.isEmpty()){
           int len=que.size();
            List<Integer> list =new ArrayList();
           while(len>0){
               TreeNode temp=que.poll();
                list.add(temp.val);
          
                if(temp.left!=null){
                    que.add(root.left);
                }
           
                if(temp.right!=null){
                    que.add(root.right);
                }
               len--;
           }
           res.add(list);
       }
        return res;
    }
}

结果

显示超出时间限制,但是我还没有发现问题所在。

出来混总是要还的
原文地址:https://www.cnblogs.com/ping2yingshi/p/14985592.html