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

Binary Tree Zigzag Level Order Traversal

时间:2015-06-10 06:31:24      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:

跟之前的解法一模一样Binary Tree Level Order Traversal I,II  不赘述

public class Solution {
    public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
        if(root==null) return res;
        LinkedList<TreeNode> q = new LinkedList<TreeNode>();
        int curNum = 1, nextNum = 0;
        boolean rv =false;
        ArrayList<Integer> cl = new ArrayList<Integer>();
        q.add(root);
        while(!q.isEmpty()){
            curNum--;
            TreeNode n = q.poll();
            cl.add(n.val);
            if(n.left!=null){
                q.add(n.left);
                nextNum++;
            }
            if(n.right!=null){
                q.add(n.right);
                nextNum++;
            }
            if(curNum==0){
                if(rv){
                    Collections.reverse(cl);
                }
                rv = !rv;
                res.add(cl);
                cl = new ArrayList<Integer>();
                curNum=  nextNum;
                nextNum=0;
            }
        }
        return res;
    }
}

 

Binary Tree Zigzag Level Order Traversal

标签:

原文地址:http://www.cnblogs.com/jiajiaxingxing/p/4565046.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!