leetCode No.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]
]

标签:Tree、Breadth-first Search、Stack
相似问题: (E) Binary Tree Level Order Traversal

题意

层序遍历数,如果深度为奇数本层从左向右顺序加入结果,如果深度为偶数本层从右向左顺序加入结果。

解题思路

广搜,每次判断一下当前深度的奇偶性,更改一下入队的左右顺序即可。

代码

public class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new LinkedList<List<Integer>>();
        if (root == null) {
            return res;
        }
        List<TreeNode> list = new LinkedList<>();
        list.add(root);
        int flag = 0;
        while (!list.isEmpty()) {
            int size = list.size();
            if (flag == 0) {
                List<Integer> cur = new LinkedList<>();
                int index = size - 1;
                while (size > 0) {
                    size --;
                    TreeNode curNode = list.get(index);
                    list.remove(index);
                    cur.add(curNode.val);
                    if (curNode.left != null) {
                        list.add(curNode.left);
                    }
                    if (curNode.right != null) {
                        list.add(curNode.right);
                    }
                    index--;
                }
                res.add(cur);
                flag = 1;
            } else if (flag == 1) {
                List<Integer> cur = new LinkedList<>();
                int index = size - 1;
                while (size > 0) {
                    size--;
                    TreeNode curNode = list.get(index);
                    list.remove(index);
                    cur.add(curNode.val);
                    if (curNode.right != null) {
                        list.add(curNode.right);
                    }
                    if (curNode.left != null) {
                        list.add(curNode.left);
                    }
                    index--;
                }
                res.add(cur);
                flag = 0;
            }
        }
        return res;
    }
}

相关链接

原题
所有题解代码(github)

你可能感兴趣的:(leetCode)