[剑指offer刷题] AcWing 45. 之字形打印二叉树(模拟,栈的应用)

思路

分层层次遍历

在每一层结束后,向队列中加入一个null

之字型打印

在每次转换层时,对level中的结果反转

题目

请实现一个函数按照之字形顺序从上向下打印二叉树。

即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
数据范围

树中节点的数量 [0,1000]


样例

输入如下图所示二叉树[8, 12, 2, null, null, 6, 4, null, null, null, null]
8
/
12 2
/
6 4
输出:[[8], [2, 12], [6, 4]]

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> printFromTopToBottom(TreeNode root) {
        boolean flag = false;
        
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (root == null) return res;
        
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        q.offer(root);
        q.offer(null);
        
        List<Integer> level = new ArrayList<Integer>();
        while (q.size() > 0) {
            TreeNode t = q.poll();
            if (t == null)
            {
                if (level.size() == 0) break;
                if (flag) Collections.reverse(level);
                res.add(new ArrayList<Integer>(level));
                level.clear();
                q.offer(null);
                
                // 取反操作必须在 #26 行之后
                flag = !flag;  // 取反操作
                continue;
            }
            
            level.add(t.val);
            if (t.left != null)
                q.offer(t.left);
            if (t.right != null)
                q.offer(t.right);
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东阳z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值