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,#,#,15,7},
    3
   / \
  9  20
   /   \
  15   7
return its zigzag level order traversal as:
[
  [3],
  [20,9],
  [15,7]
]

Binary Tree Level Order Traversal的变形题目,我们只要在上一题的基础上维护一个变量level,来判断是偶数层还是奇数层,如果是奇数层我们就正序添加,如果是偶数层就倒叙添加。我们可以用链表的addFirst() 方法。代码如下:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        LinkedList<Integer> list = new LinkedList<Integer>();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        if(root == null) return result;
        queue.offer(root);
        int count = 1, level = 1, helper = 0;
        while(!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            count --;
            if(level % 2 == 1) {
                list.add(cur.val);
            } else {
                list.addFirst(cur.val);
            }
            if(cur.left != null) {
                queue.offer(cur.left);
                helper ++;
            }
            if(cur.right != null) {
                queue.offer(cur.right);
                helper ++;
            }
            if(count == 0) {
                result.add(new LinkedList<Integer>(list));
                count = helper;
                helper = 0;
                level ++;
                list.clear();
            }
        }
        return result;
    }
}

你可能感兴趣的:(java,bfs)