首页 > 其他 > 详细

[Lintcode]Binary Tree Zigzag Level Order Traversal

时间:2015-10-08 00:17:58      阅读:110      评论:0      收藏:0      [点我收藏+]

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

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

SOLUTION :

这题跟level order的模版都是一样的,用queue进行BFS,只不过中间要加一些约束条件,调整level list里面结果的顺序。一般来说碰到类似奇偶循环的约束条件,就判断一下(n % 2 == 0)。很简单的小技巧,记住就好。 

具体看代码,备注调整位置:

public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: A list of lists of integer include 
     *          the zigzag level order traversal of its nodes‘ values 
     */
    public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        if (root == null){
            return result;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        int n = 0;// 增加进行判断的参数
        while (!queue.isEmpty()){
            ArrayList<Integer> list = new ArrayList<Integer>();
            int size = queue.size();
            for (int i = 0; i < size; i++){
                TreeNode cur = queue.remove();
                //这里进行list.add的约束
                if (n % 2 == 0){
                    list.add(cur.val);
                } else {
                    list.add(0, cur.val);
                }
                if (cur.left != null){
                    queue.offer(cur.left);
                }
                if (cur.right != null){
                    queue.offer(cur.right);
                }
            }
            n++;// 以及这里
            result.add(list);
        }
        return result;
    }
}    

  

[Lintcode]Binary Tree Zigzag Level Order Traversal

原文:http://www.cnblogs.com/tritritri/p/4859874.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!