之字形打印二叉树

之字形打印二叉树

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

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

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

思路:
这个题与按层打印二叉树基本一样,改一下代码就好,只不过对每一层的节点的存有变化,
由于是之子结构,第一层是正序第二层就得是倒序,就得用一个boolean变量来标记这个方向,每打印完一层就要翻转
正序的时候是正常的把每一层的节点按顺序往list集合里放,倒序的时候就要倒着往集合里放,这时候得用一个栈来辅助,
先正序把元素放入栈中,然后再把栈里的元素放入该层的集合中

/**
 * 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) {
                List<List<Integer>> res= new ArrayList<>();
        if(root==null){
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        TreeNode head = null;
        int nextnodecount = 1;
        int nodecount = 0;
        boolean direct = false;
        while(!queue.isEmpty()) {
            nodecount = nextnodecount;//把之前的next给现在的
            nextnodecount = 0;//从新开始计数
            List<Integer> list = new ArrayList<>();
            Stack<Integer> stack = new Stack<>();
            for (int i = 1; i <= nodecount; i++) {
                head = queue.poll();
                if (!direct)
                    list.add(head.val);
                if (direct)
                    stack.push(head.val);

                if (head.left != null) {
                    queue.offer(head.left);
                    nextnodecount++;

                }
                if (head.right != null) {
                    queue.offer(head.right);
                    nextnodecount++;
                }
               
            }
             direct = !direct;//下一层的层的方向要换
            if (direct)
                res.add(list);
            if(!direct) {
               List <Integer>list1 = new ArrayList<>();
               while(!stack.isEmpty()){
                   list1.add(stack.pop());
               }
                res.add(list1);
            }
        }
        return res;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值