二叉树的层序遍历

class Solution {
    public List> levelOrder(TreeNode root) {
        List> ret = new ArrayList>();
        if (root == null) {
            return ret;
        }

        Queue queue = new LinkedList();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List level = new ArrayList();
            int currentLevelSize = queue.size();
            for (int i = 1; i <= currentLevelSize; ++i) {
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            ret.add(level);
        }
        
        return ret;
    }
}

你可能感兴趣的:(栈和队列_new,windows)