绘制二叉树

首先对所要绘制的二叉树进行复制及扩展,即构造映像树

递归方式构造:

public static<T>TNodeShadow buildShadowTree(TNode t,int level)
	{
		TNodeShadow newNode=null;
		String str;
		if(t!=null)
		{
			newNode=new TNodeShadow();
			TNodeShadow newLeft=buildShadowTree(t.left,level+1);
			newNode.left=newLeft;
			str=(t.nodeValue).toString();
			newNode.nodeValueStr=str;
			newNode.level=level;
			newNode.column=TNodeShadow.columnValue;
			TNodeShadow.columnValue++;
			TNodeShadow newRight=buildShadowTree(t.right,level+1);
			newNode.right=newRight;
		}
		return newNode;
	}


利用映像树绘制:

public static<T> String displayTree(TNode<T> t,int maxCharacter)
	{
		LinkedQueue<TNodeShadow> q=new LinkedQueue<TNodeShadow>();
		String displayStr="";
		int colWidth=maxCharacter+1;
		int currLevel=0,currCol=0;
		TNodeShadow.columnValue=0;
		if(t==null)
			return displayStr;
		TNodeShadow shadowRoot=buildShadowTree(t,0);
		TNodeShadow currNode;
		q.push(shadowRoot);
		while(!q.isEmpty())
		{
			
			currNode=q.pop();
			if(currNode.level>currLevel)
			{
				currLevel=currNode.level;
				currCol=0;
				displayStr+='\n';
			}
			if(currNode.left!=null)
			{
				q.push(currNode.left);
			}
			if(currNode.right!=null)
			{
				q.push(currNode.right);
			}
			for(int i=0;i<currNode.column;i++)
			{
				displayStr+=' ';
			}
			displayStr+=currNode.nodeValueStr;
			currCol++;
		}
		displayStr+="\n";
		clearShadowTree(shadowRoot);
		return displayStr;
	}

绘制完成后递归清除映像树:

public static<T> void clearShadowTree(TNodeShadow t)
	{
		if(t!=null)
		{
			clearShadowTree(t.left);
			clearShadowTree(t.right);
			t=null;
		}
	}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值