牛客题霸NC15题解

求二叉树的层序遍历

牛客题霸NC15

难度:Medium

二叉树的层序遍历使用队列来实现,代码如下:

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<>();
        }
        
        
        LinkedList<TreeNode> queue = new LinkedList<>();
        ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
        ArrayList<Integer> list;
        queue.offer(root);
        
        while(!queue.isEmpty()){
            
            list = new ArrayList<>();
            TreeNode tail = queue.peekLast();
            
            while(true){
                TreeNode cur = queue.poll();
                list.add(cur.val);
                if(cur.left != null){
                    queue.offer(cur.left);
                }
                if(cur.right != null){
                    queue.offer(cur.right);
                }
                if(cur == tail){
                    break;
                }
            }
            
            lists.add(list);
        }
        
        
        return lists;
        
        
    }
}
posted @ 2020-11-09 14:27  阿柒~  阅读(94)  评论(0编辑  收藏  举报