二刷103. Binary Tree Zigzag Level Order Traversal

Medium
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).

Have you met this question in a real interview? Yes

Example
Given binary tree {3,9,20,#,#,15,7},

  3
 / \
9  20
  /  \
 15   7

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

比上次写得稍微简洁一点

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */


public class Solution {
    /*
     * @param root: A Tree
     * @return: A list of lists of integer include the zigzag level order traversal of its nodes' values.
     */
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        // write your code here
        List<List<Integer>> res = new ArrayList<>();
        if (root == null){
            return res;
        }
        int count = 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            List<Integer> level = new ArrayList<>();
            for (int i = 0; i < size; i++){
                TreeNode curt = queue.poll();
                if (curt.left != null){
                    queue.offer(curt.left);
                }
                if (curt.right != null){
                    queue.offer(curt.right);
                }
                if (count % 2 == 0){
                    level.add(curt.val);
                } else {
                    level.add(0, curt.val);
                }
            }
            count++;
            res.add(level);
        }
        return res;
    }
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/e4e2ca731147
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞