码迷,mamicode.com
首页 > 其他好文 > 详细

[Lintcode]Binary Tree Zigzag Level Order Traversal

时间:2015-10-08 00:20:08      阅读:202      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!