广度优先

LeetCode 103 二叉树的锯齿形层序遍历

class Solution {
    public List> zigzagLevelOrder(TreeNode root) {
        List> result = new ArrayList>();
        if (null == root) {
            return result;
        }
        Queue nodeQueue = new LinkedList();
        nodeQueue.offer(root);
        Boolean isLeft = true;

        while (!nodeQueue.isEmpty()) {
            Deque dequeue = new LinkedList<>();
            Integer size = nodeQueue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = nodeQueue.poll();
                if (isLeft) {
                    dequeue.offerLast(node.val);
                } else {
                    dequeue.offerFirst(node.val);
                }
                if (null != node.left)
                    nodeQueue.offer(node.left);
                if (null != node.right)
                    nodeQueue.offer(node.right);
            }
            result.add(new ArrayList(dequeue));
            isLeft = !isLeft;
        }

        return result;
    }
}

你可能感兴趣的:(广度优先)