Leetcode 103. Binary Tree Zigzag Level Order Traversal

Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]

题意:这道题可以看做102的followup,也是按层遍历二叉树,加了一个条件,一层从左到右,一层从右到左,交叉顺序。

思路:参考102题的宽度优先搜索的思路,只需要额外加一个布尔标志isLeft,初始为true,每遍历完一层isLeft = !isLeft。为false的时候代表需要从右到做遍历,只需要把当前层的list反转即可。

public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
    List<List<Integer>> res = new ArrayList<>();
    if (root == null) {
        return res;
    }

    boolean isLeft = true;
    Queue<TreeNode> q = new LinkedList<>();
    q.offer(root);
    while (!q.isEmpty()) {
        int size = q.size();
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            TreeNode cur = q.poll();
            list.add(cur.val);
            if (cur.left != null) {
                q.offer(cur.left);
            }
            if (cur.right != null) {
                q.offer(cur.right);
            }
        }
        //从右到左,反转list
        if (!isLeft) {
            Collections.reverse(list);
        }
        res.add(list);
        isLeft = !isLeft;
    }

    return res;
}
    原文作者:ShutLove
    原文地址: https://www.jianshu.com/p/a300c9b8a1cd
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞