Np16、输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印。

题目(微软):
输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印。 
例如输入
     8
    /   \
  6    10

 / \     /  \

5 7  9  11

输出 8 6 10 5 7 9 11。


解题思路:

编程之美3-10...分层遍历二叉树

思想很简单...一个队列,先将根节点入队....然后开始循环

当一个节点出队之前,将它的左子节点、右子节点入队,然后出队输出该节点的信息...

直到队列中的长度为0。


public class Q16 {
	public static void out(Node head)
	{
		ArrayList<Node> list = new ArrayList<Node>();
		list.add(head);
		
		while(list.size()>0)
		{
			Node node = list.get(0);
			System.out.println(node.data);
			if(node.leftChild !=null)
				list.add(node.leftChild);
			if(node.RightChild != null)
				list.add(node.RightChild);
			
			list.remove(0);
		}
	}
	public static void main(String[] args) {
		Node a = new Node(8);
		Node b = new Node(6);
		Node c = new Node(10);
		Node d = new Node(5);
		Node e = new Node(7);
		Node f = new Node(9);
		Node g = new Node(11);
		
		a.leftChild = b;
		a.RightChild = c;
		b.leftChild = d;
		b.RightChild = e;
		c.leftChild = f;
		c.RightChild = g;
		
		out(a);
	}	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值