栈-N103-二叉树的锯齿形层次遍历

2019-04-04  本文已影响0人  三次元蚂蚁

题目

思路

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> result = new LinkedList<>();
        if (root == null) {
            return result;
        }
        
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.push(root);
        TreeNode top;
        boolean isEven = false;
        int size;
        while (!queue.isEmpty()) {
            List<Integer> levelList = new LinkedList<>();
            size = queue.size();
            for (int i = 0; i < size; ++i) {
                top = queue.poll();
                if (isEven) {
                    levelList.add(0, top.val);
                } else {
                    levelList.add(top.val);
                }
                if (top.left != null) {
                    queue.offer(top.left);
                }
                if (top.right != null) {
                    queue.offer(top.right);
                }
            }
            result.add(levelList);
            isEven = !isEven;
        }
        
        return result;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读