数组模拟队列

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>> list = new ArrayList<>();
        ArrayList<Integer> curList = new ArrayList<>();

        // 用于记录当前层的节点个数
        int curNum = 1;
        // 用于记录下一层的节点个数
        int nextNum = 0;

        // 数组模拟队列
        int N = 100000 + 10;
        TreeNode[] queue = new TreeNode[N];
        int hh = 0;
        int tt = -1;
        queue[++tt] = root;
        while (hh <= tt) {
            TreeNode poll = queue[hh++];
            curList.add(poll.val);
            curNum--;
            if (poll.left != null) {
                queue[++tt] = poll.left;
                nextNum++;
            }
            if (poll.right != null) {
                queue[++tt] = poll.right;
                nextNum++;
            }
            if (curNum == 0) {
                // update
                curNum = nextNum;
                nextNum = 0;
                list.add(curList);
                curList = new ArrayList<>();
            }
        }

        return list;
    }
}