0
点赞
收藏
分享

微信扫一扫

面试必刷TOP101:26、求二叉树的层序遍历

题目

面试必刷TOP101:26、求二叉树的层序遍历_java

题解

 public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
        // write code here
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        if(root == null){
            return res;
        }
        ArrayList<TreeNode> listCru = new ArrayList<>();
        listCru.add(root);
        int count = 0;
        int n=1;
        while(count < n){
            n = listCru.size();
            ArrayList<Integer> listres = new ArrayList<>();
            for(;count<n;count++){
                listres.add(listCru.get(count).val);
                if(listCru.get(count).left != null){
                    listCru.add(listCru.get(count).left);
                }
                if(listCru.get(count).right != null){
                    listCru.add(listCru.get(count).right);
                }
            }
            n = listCru.size();
            res.add(listres);
        }
        return res;
    }

举报

相关推荐

0 条评论