剑指offer (60)

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

思路 : 树的的广度优先遍历 法二
与上题的不同在于,将两个栈变为两个队列,即实现了不同的共能,
当然,在具体偶数层的时候也是不一样,前一题是变为先入右子树,再入左子树,这题则无需改变

	public static ArrayList<ArrayList<Integer>> print(TreeNode pRoot) {
		ArrayList<ArrayList<Integer>> res = new ArrayList<>();
		if (pRoot == null) {
			return res;
		}
		LinkedList<TreeNode>queue1 = new LinkedList<>();
		LinkedList<TreeNode>queue2 = new LinkedList<>();
		int deepth = 1;
		queue1.add(pRoot);
		while (!queue1.isEmpty() || !queue2.isEmpty()) {
			// 奇数层
			if (deepth % 2 != 0) {
				ArrayList<Integer> list1 = new ArrayList<>();//用来暂存结果
				while (!queue1.isEmpty()) {
					TreeNode cur = queue1.pop();
					list1.add(cur.value);
					if (cur.left != null) {
						queue2.add(cur.left);
					}
					if (cur.right != null) {
						queue2.add(cur.right);
					}
				}
				if (!list1.isEmpty()) {
					res.add(list1);
					deepth++;
				}
			}
			// 偶数层
			else {
				ArrayList<Integer> list2 = new ArrayList<>();//用来暂存结果
				while (!queue2.isEmpty()) {
					TreeNode cur = queue2.pop();
					list2.add(cur.value);
					if (cur.left != null) {
						queue1.add(cur.left);
					}
					if (cur.right != null) {
						queue1.add(cur.right);
					}
				}
				if (!list2.isEmpty()) {
					res.add(list2);
					deepth++;
				}
			}
		}
		return res;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值