先序、中序构造一棵唯一的二叉树

直接上代码:

public class BinaryTree
{
	public BinaryTree(String pre,String in)
	{
		makeTree(pre,in);
	}
	public static void main(String[] args)
	{
		BinaryTree tree=new BinaryTree("ABDCEGFHI","DBAEGCHFI");
		tree.preOrder();
	}
	public void preOrder()
	{
		preOrder(this.root);
	}
	public void preOrder(BinaryTreeNode n)
	{
		if(n!=null)
		{
			visitNode(n);
			preOrder(n.left);
			preOrder(n.right);
        }
	}
	private void visitNode(BinaryTreeNode n)
	{
		if(n!=null)
		   System.out.println(n.ele);
	}
	private void makeTree(String pre,String in)
	{
		if(pre!=null)
		{
			root=new BinaryTreeNode(null,pre.charAt(0),null);
			if(pre.length()==1)
			    return;
			int pareIndex=in.indexOf(pre.charAt(0));
			if(pareIndex>0&&pareIndex<in.length()-1)
			{
		        makeTree(certainNode(pre.substring(1,pareIndex+1)),in.substring(0,pareIndex),root,true);
		        makeTree(certainNode(pre.substring(pareIndex+1)),in.substring(pareIndex+1),root,false);
            }
            else if(pareIndex==0)
            {
				makeTree(certainNode(pre.substring(1)),in.substring(1),root,false);
			}
			else
			{
				makeTree(certainNode(pre.substring(1)),in.substring(1,pareIndex-1),root,true);
			}
	    }
	}
	private void makeTree(String pre,String in,BinaryTreeNode pare,boolean isL)
	{
		      //~ String s="pre : "+pre+" in : "+in+" right or left :"+((isL)?"left":"right");
		      //~ System.out.println(s);
		      BinaryTreeNode parent=null;
   	          if(pre==null)
   	              return;
	          if(isL)
	             parent=pare.left=new BinaryTreeNode(null,pre.charAt(0),null);
	          else
	             parent=pare.right=new BinaryTreeNode(null,pre.charAt(0),null);
	          if(pre.length()==1)
	             return;
	           int pareIndex=in.indexOf(pre.charAt(0));
	           if(pareIndex>0&&pareIndex<in.length()-1)
	           {
				   makeTree(certainNode(pre.substring(1,pareIndex+1)),in.substring(0,pareIndex),parent,true);
				   makeTree(certainNode(pre.substring(pareIndex+1)),in.substring(pareIndex+1),parent,false);
			   }
			   else if(pareIndex==0)
			   {
				   makeTree(certainNode(pre.substring(1)),in.substring(pareIndex+1),parent,false);
			   }
			   else
			   {
				   makeTree(certainNode(pre.substring(1)),in.substring(0,pareIndex),pare.left,true);
			   }
	}
	private String certainNode(String s)
	{
		if(s.length()==0)
		   return null;
		else
		    return s;
	}
	private BinaryTreeNode root;
	private BinaryTreeNode curr; 
	private class BinaryTreeNode
	{
		public BinaryTreeNode left;
		public BinaryTreeNode right;
		Object ele;
		BinaryTreeNode(BinaryTreeNode l,Object o,BinaryTreeNode r)
		{
			left=l;
			right=r;
			ele=o;
		}
	}		
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值