103. Binary Tree Zigzag Level Order Traversal

本文介绍了一种实现二叉树锯齿形层序遍历的方法,使用两个队列交替存放奇数层和偶数层的节点,并通过栈来反转偶数层节点的顺序,最终得到按层且每层逆序交错的节点值。
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
   public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        Queue<TreeNode>queue1 = new LinkedList<>();//这个是用了放偶数层的节点的;
        Queue<TreeNode>queue2 = new LinkedList<>();//这个是用来放奇数成的节点的;
        Stack<TreeNode>stack  = new Stack<>();
        List<Integer> list = new ArrayList<>();
        List<List<Integer>>ll = new ArrayList<>();
        if (root==null)return ll;
        queue1.add(root);
        int i=0;
       while (!queue1.isEmpty()||!queue2.isEmpty()){
           list =new ArrayList<>();
           //因为我是往队列里先加入右节点再加入左节点,所以偶数层的时候需要用stack颠倒输出的数。
           if (i%2==0){
               while (!queue1.isEmpty()) {
                   TreeNode node = queue1.poll();
                   stack.push(node);
                   if (node.right!=null)queue2.add(node.right);
                   if (node.left!=null)queue2.add(node.left);
               }
               while (!stack.isEmpty()){
                   list.add(stack.pop().val);
               }
               ll.add(list);
               i++;
               continue;
           }else {
               while (!queue2.isEmpty()){
                   TreeNode node = queue2.poll();
                   list.add(node.val);
                   if (node.right!=null)queue1.add(node.right);
                   if (node.left!=null)queue1.add(node.left);
               }
               ll.add(list);
               i++;
               continue;
           }
       }
       return ll;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值