周三第十一题   之字形打印二叉树  - Java

 AcWing打卡活动

《剑指Offer》打卡活动 

周三第十一题   之字形打印二叉树 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 * 思路
 * 和上题的区别,
 * a. 一层从左往右
 * b. 一层从右往左
 * 所以需要记录两个队列,一个队列记录情况a-记为a队列,一个队列记录情况b-记为b队列
 * 使用一个二维数组记录当前打印的层,第一层代表从左往右打印,第二层代表从右往左打印
 * 当a队列打印完后,在打印b队列,在打印a队列。如此往复
 * 
 */
class Solution {
    public List<List<Integer>> printFromTopToBottom(TreeNode root) {
        List<List<Integer>> printList = new ArrayList();
        if(root == null) {
            return printList;
        }
        List<Integer> elementList = new ArrayList();
        
        List<Stack<TreeNode>> stackList = new ArrayList(2);
        Stack<TreeNode> currentStack = new Stack();
        Stack<TreeNode> nextStack = new Stack();
        stackList.add(currentStack);
        stackList.add(nextStack);
        currentStack.push(root);
        TreeNode node;
        
        int current = 0;
        int next = 1;
        while(!stackList.get(current).empty() || !stackList.get(next).empty()) {
            // 弹出当前栈的栈顶
            node = stackList.get(current).pop();
            
            elementList.add(node.val);
            if(current == 0) { // 等于0,则表示当前层数为从右往左打印
                // 在栈中,先压入左节点,在压入右节点,打印时会先打印右节点在打印左节点
                if(node.left != null) { 
                    stackList.get(next).push(node.left); // 压入到下一层中,即get(next)
                }
                if(node.right != null) {
                    stackList.get(next).push(node.right);// 压入到下一层中,即get(next)
                }
            } else { // 否则相反
                if(node.right != null) {
                    stackList.get(next).push(node.right);// 压入到下一层中,即get(next)
                }
                if(node.left != null) { 
                    stackList.get(next).push(node.left); // 压入到下一层中,即get(next)
                }
            
            }
            // stackList.get(current).empty() 的时候,代表当前层以及打印完成,重新初始化各个参数
            if(stackList.get(current).empty()) {
                current = 1 - current;
                next = 1 - next;
                printList.add(elementList);
                elementList = new ArrayList();
            }
            
        }
        return printList;
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值