您的位置:首页 > 其它

【笔试】40、从上往下打印二叉树

2015-09-03 10:02 375 查看
/****************************************************************************************
 *题目:从上往下打印二叉树
 *		从上往下打印出二叉树的每个节点,同一层的结点按照从左到右的顺序打印。例如输入图4.5中的二叉树,则依次打印出8、 6、 10、 5、 7、 9、 11
 *								8
 *						/				\
 *					   6				10
 *				  /		   \	    /		\
 *				 5		    7      9		 11
 *
 *		ArrayDeque他是Deque 接口的大小可变数组的实现。数组双端队列没有容量限制;它们可根据需要增加以支持使用。它们不是线程安全的;
 *		此类很可能在用作堆栈时快于 Stack,在用作队列时快于 LinkedList。 
 *
 *		LinkedBlockingDeque  一个基于已链接节点的、任选范围的阻塞双端队列。 
 *		可选的容量范围构造方法参数是一种防止过度膨胀的方式。如果未指定容量,那么容量将等于 Integer.MAX_VALUE。
 *		只要插入元素不会使双端队列超出容量,每次插入后都将动态地创建链接节点。 大多数操作都以固定时间运行(不计阻塞消耗的时间)。
 *时间:2015年9月3日09:03:36
 *文件:PrintTreeFromTopToBottom.java
 *作者:cutter_point
 ****************************************************************************************/
package bishi.Offer50.y2015.m09.d03;

import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;

import org.junit.Test;

import bishi.Offer50.y2015.m08.d26.*;

public class PrintTreeFromTopToBottom
{
	public void print(BinaryTreeNode pRoot) throws Exception
	{
		//鲁棒性检查
		if(pRoot == null)
		{
			throw new Exception("此队列为空");
		}
		//ArrayDeque他是Deque 接口的大小可变数组的实现。数组双端队列没有容量限制;它们可根据需要增加以支持使用。它们不是线程安全的;
		Queue<BinaryTreeNode> queue = new LinkedBlockingDeque<BinaryTreeNode>();
		//放入第一个根节点
		queue.add(pRoot);
		while(queue.size() > 0)
		{
			//首先输出对应的队首元素,然后压入队列左右子树
			BinaryTreeNode temp = new BinaryTreeNode();
			temp = queue.remove();	//获取队首元素
			System.out.print(temp.m_nValue + "\t");
			//把做左右的节点进入队列
			if(temp.m_pLeft != null)
			{
				queue.add(temp.m_pLeft);
			}//if
			//判断右边是否有节点,如果有的话,就进入队列
			if(temp.m_pRight != null)
			{
				queue.add(temp.m_pRight);
			}//if
		}//while
	}

	//						1
	//				/				\
	//			   2				 3
	//		  /	 	    		/		  \
	//		 4		   		   5		   6
	//			\						/
	//			 7	 				   8
	//
	//我们的二叉树,用这个题的方法遍历的结果是
	//1  2  3  4  5  6  7  8
	//
	@Test
	public void test() throws Exception
	{
		int preorder[] = {1,2,4,7,3,5,6,8};
		int inorder[] = {4,7,2,1,5,3,8,6};
		BinaryTree bt = new BinaryTree();
		bt.construct(preorder, inorder);
		BinaryTreeNode test = bt.root;
		this.print(test);
	}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: