剑指Offer59:按之字形顺序打印二叉树

题目:给定一个二叉树,返回该二叉树的之字形层序遍历,(第一层从左向右,下一层从右向左,一直这样交替)

示例

输入:{8,6,10,5,7,9,11}
返回值:[[8],[10,6],[5,7,9,11]]

解法:正常进行先序遍历,等到从右向左的时候把ArrayList逆转。

import java.util.*;
public class Solution {
    public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> arrays = new ArrayList<>();
        if (pRoot == null)
            return arrays;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(pRoot);
        
        boolean flag = false;
        
        while(queue.size()!=0){
            int size = queue.size();
            ArrayList<Integer> current = new ArrayList<>();
            while(size > 0){
                TreeNode temp = queue.poll();
                current.add(temp.val);
                if(temp.left != null)
                    queue.add(temp.left);
                if(temp.right != null)
                    queue.add(temp.right);
                
                size--;
            }
            if(flag)
                Collections.reverse(current);
            flag = !flag;
            arrays.add(current);
        }
        return arrays;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值