剑指Offer(Java实现)把二叉树打印成多行

题目描述

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

解题思路

利用辅助空间链表或队列来存储节点,每层输出。

代码实现

import java.util.ArrayList;
import java.util.LinkedList;

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        if (null == pRoot) {
            return res;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(pRoot);
        ArrayList<Integer> list = new ArrayList<>();
        int start = 0;
        int end = 1;
        
        while (!queue.isEmpty()) {
            TreeNode node = queue.pop();
            start++;
            list.add(node.val);
            if (null != node.left) {
                queue.offer(node.left);		// 也可用 queue.add(node.left);
            }
            if (null != node.right) {
                queue.offer(node.right);	// 也可用 queue.add(node.right);
            }
            
            if (start == end) {
                start = 0;
                end = queue.size();
                res.add(new ArrayList<>(list));
                list.clear();
            }
        }
        return res;
    }
}

注意

if (start == end) {
	start = 0;
    end = queue.size();
    res.add(new ArrayList<>(list));
    list.clear();
}

start 用于记录当前节点在其所在层中的位置;end 用于记录当前节点所在层的节点个数。

当 start == end 时,则说明当前层的节点都以记录完成,存入ArrayList中;此时,需要将start重新设为0,而且,当前队列中剩余元素皆为下一层中的节点,故需要将end设置为 queue.size(),并清除list,等待下一次遍历的节点存储。

if (null != node.left) {
	queue.offer(node.left);		// 也可用 queue.add(node.left);
}
if (null != node.right) {
	queue.offer(node.right);	// 也可用 queue.add(node.right);
}

offer属于 offer in interface Deque<E>,add 属于 add in interface Collection<E>。

当队列为空时候,使用add方法会报错,而offer方法会返回false。

作为List使用时,一般采用add / get方法来 压入/获取对象。

作为Queue使用时,才会采用 offer/poll/take等方法作为链表对象时,offer等方法相对来说没有什么意义这些方法是用于支持队列应用的。

总的上来说,add() 与 offer() 基本情况可以通用。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值