首页 > 代码库 > Binary Tree Zigzag Level Order Traversal

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]
]

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:
很简单的一个,比Binary Tree Level Order Traversal多了一个方向标志(Zigzag的方向性),

/**
 * Definition for binary tree
 * 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>> list = new LinkedList<List<Integer>>();//返回结果
        Queue<TreeNode> queue = new LinkedList<TreeNode>();//队列,使用BFS遍历
        int level = 0;//记录某一层进队的元素数
        int count = 0;//计数
        if(root == null){
            return list;
        }
        queue.offer(root);
        level++;
        TreeNode p = null;
        boolean flag = true;//标志Zigzap的方向
        while(queue.size() > 0){
            int nextLevel = 0;//下一层进队的元素数
            List<Integer> tmp = new ArrayList<Integer>();//中间存储每一行的结果
            while(count < level){
                p = queue.poll();//出队
                if(p.left != null){
                    queue.offer(p.left);
                    nextLevel++;
                }
                if(p.right != null){
                    queue.offer(p.right);
                    nextLevel++;
                }
                if(flag){
                    tmp.add(p.val);
                }else{
                    tmp.add(0,p.val);
                }
                count ++;
            }
            list.add(tmp);
            count = 0;
            level = nextLevel;
            flag = !flag;
        }
        return list;
    }
}
Runtime: 227 ms

Binary Tree Zigzag Level Order Traversal