Leetcode: Binary Tree Zigzag Level Order Traversal 理解分析

题目大意:给定一个二叉树,返回zigzag层序遍历,即返回每层的元素,并且一层从左向右,下一层从右向左的顺序。

理解:在层序遍历二叉树的基础上增加要求,奇数层的正序,偶数层的逆序。实现过程与层序遍历返回每层元素类似(http://blog.csdn.net/blog_szhao/article/details/23860125),只是在处理存储每层元素时,设置一个标志tag,若tag为真,则逆序存储;否则,正序存储。

例如:给定二叉树[3,9,20,#,#,15,7],返回[[2], [20,9], [15,7]]。

实现:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList<ArrayList<Integer>> arr =  new ArrayList<ArrayList<Integer>>();
    public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
        if(root == null)    return arr;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        boolean tag = false; // 标志
        int visit = 1, nextVisit = 0;
        while(!queue.isEmpty()) {
            TreeNode p = queue.peek();
            ArrayList<Integer> a = new ArrayList<Integer>();
            while(visit > 0 && p != null) {
                if(tag) a.add(0,p.val); // 逆序
                else a.add(p.val); // 正序
                if(p.left != null) {
                    nextVisit ++;
                    queue.offer(p.left);
                }
                if(p.right != null) {
                    nextVisit ++;
                    queue.offer(p.right);
                }
                queue.poll();
                if(!queue.isEmpty())
                    p = queue.peek();
                visit --;
            }
            if(tag) tag = false; // change the next store order
            else tag = true;
            arr.add(a);
            if(nextVisit == 0) break;
            visit = nextVisit;
            nextVisit = 0;
        }
        return arr;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值