剑指Offer-32 Ⅲ

从上到下打印二叉树

请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。

核心思想:判断当前层是第几层,来决定是顺序打印还是逆序打印

/**
 * 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>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        if(root != null){
            queue.add(root);
        }
        //打印顺序标志,每打印一行就反转一次,true默认从左向右
        //如果需要从右向左打印,先保存到栈中,再依次弹出加入到List集合
        Boolean flag = true;
        while(!queue.isEmpty()){
            List<Integer> temp = new ArrayList<Integer>();
            if(flag){
                //正向打印
                for(int i = queue.size(); i > 0; i--){
                    TreeNode cur = queue.poll();
                    temp.add(cur.val);
                    if(cur.left != null){
                        queue.add(cur.left);
                    }
                    if(cur.right != null){
                        queue.add(cur.right);
                    }
                }
                list.add(temp);
                flag = !flag;
            }else{
                //反向打印
                Stack<Integer> stack = new Stack<Integer>();
                for(int i = queue.size(); i > 0; i--){
                    TreeNode cur = queue.poll();
                    stack.push(cur.val);
                    if(cur.left != null){
                        queue.add(cur.left);
                    }
                    if(cur.right != null){
                        queue.add(cur.right);
                    }
                }
                //出栈,加入到temp里
                while(!stack.isEmpty()){
                    temp.add(stack.pop());
                }
                flag = !flag;
                list.add(temp);
            }
        }

        return list;

    }
}

耗时:2ms

优化:使用结果集中的元素个数来判断是第几层,并且使用LinkedList作为temp,LinkedList里有加入到队列头部和尾部的操作,耗时更短

if(list.size() % 2 == 0) tmp.addLast(node.val); // 偶数层 -> 队列头部
else tmp.addFirst(node.val); // 奇数层 -> 队列尾部

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值