剑指Offer——P32(1.从上到下打印二叉树)(2.分行从上到下打印二叉树)

P32_1:从上往下打印出二叉树的每个节点,同层节点从左至右打印。

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

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

    }

}
*/
public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
		ArrayList<Integer> list = new ArrayList<>();
		if (root == null)
			return list;
		Queue<TreeNode> que = new LinkedList<>();
		que.add(root);
		while (!que.isEmpty()) {
			TreeNode item = que.poll();
			list.add(item.val);
			if (item.left != null)
				que.add(item.left);
			if (item.right != null)
				que.add(item.right);
		}
		return list;
	}
}

P32_2:  分行从上到下打印二叉树

从上到下打印二叉树,同一层的节点按从从左到右的顺序打印,每一层打印到一行。

package jianzhi_offer;
import java.util.LinkedList;
import java.util.Queue;
import jianzhi_offer.Print.TreeNode;
public class P32_2_Solution {
/*
 * 二叉树按层打印
 * 解题思路:还是按照层次遍历的思想,增加两个变量toBePrinted当前层还没有打印的节点; nextLevel表示下一层中的节点数
 */
	public void printLevel(TreeNode root) {
		if(root == null)
			return;
		Queue<TreeNode> que = new LinkedList<>();
		que.offer(root);
		int toBePrinted = 1;
		int nextLevel = 0;
		while(!que.isEmpty()) {
			TreeNode temp = que.peek();
			System.out.print(temp.val);
			que.poll();
			toBePrinted--;
			if(root.left != null) {
				que.offer(root.left);
				nextLevel++;
			}
			if(root.right != null) {
				que.offer(root.right);
				nextLevel++;
			}
			if(toBePrinted == 0) {
				System.out.println();
				toBePrinted = nextLevel;
				nextLevel = 0;
			}
		}	
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值