题解 | #求二叉树的层序遍历#

求二叉树的层序遍历

https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型ArrayList<ArrayList<>>
     */
    public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
        // write code here
        if(root == null){
            return new ArrayList<>();
        }
        ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
        LinkedList<TreeNode> dic = new LinkedList<>();
        dic.add(root);
        
        while(!dic.isEmpty()){
            ArrayList<Integer> arr = new ArrayList<>();
            int tmp1 = dic.size();
            for(int i = 0; i < tmp1; i++){
                TreeNode tmp = dic.removeFirst();
                arr.add(tmp.val);
                if(tmp.left != null){
                    dic.add(tmp.left);
                }
                if(tmp.right != null){
                    dic.add(tmp.right);
                }
            }
            ans.add(arr);
        }

        return ans;
    }
}

全部评论

相关推荐

我就是0offer糕手:北大不乱杀
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务