数据结构之树

/*
 *@date:08-07-06

 *@descript:树的实现与应用

 **/

public class TreeNode1

{

	public String data;//数据元素

	public TreeNode1 left,right;//指向左,右孩子的链

	

	

	public TreeNode1()//无参构造函数

	{

		this("?");	

	}

	public TreeNode1(String d)

	{

		data=d;

		left=right=null;

	}

	public void preorder(TreeNode1 p)//先根次序遍历二叉树 

	{

		if(p!=null)

		{

			System.out.print (p.data+" ");

			preorder(p.left);

			preorder(p.right);

		}

	}

	public void inorder(TreeNode1 p)//中根次序遍历二叉树

	{

		if(p!=null)

		{

			inorder(p.left);

			System.out.print (p.data+" ");

			inorder(p.right);			

		}

	}

	public void postorder(TreeNode1 p)

	{

		if(p!=null)

		{

			postorder(p.left);

			postorder(p.right);

			System.out.print (p.data+" ");

		}

	}

}



class Tree1

{

	protected TreeNode1 root;//根节点

	

	public Tree1()

	{

		root=null;

	}

	public Tree1(String prestr,String instr)//构造函数

	{

		root=enter(prestr,instr);

	}

	public void preorderTraversal()

	{

		System.out.print("先根次序:");

		if(root!=null)

		{

			root.preorder(root);

		}

		System.out.println ();

	}

	public void inorderTraversal()

	{

		System.out.print("中根次序:");

		if(root!=null)

		{

			root.inorder(root);

		}

		System.out.println ();

	}

	public void postorderTraversal()

	{

		System.out.print("后根次序:");

		if(root!=null)

		{

			root.postorder(root);

		}

		System.out.println ();

	}

	

	public TreeNode1 enter(String prestr,String instr)

	{

		TreeNode1 p=null;

		int k,n;

		String first,presub,insub;

		n=prestr.length();

		if(n>0)

		{

			System.out.print("prestr="+prestr+"/t instr="+instr);

			first=prestr.substring(0,1);//取串的第1个字符作为根

			p=new TreeNode1(first);//建立节点

			k=instr.indexOf(first);//确定根在中根序列中的位置

			System.out.println ("/t first="+first+"/t k="+k);

			presub=prestr.substring(1,k+1);

			insub=instr.substring(0,k);

			p.left=enter(presub,insub);//建立左子树

			presub=prestr.substring(k+1,n);

			insub=instr.substring(k+1,n);

			p.right=enter(presub,insub);//建立右子树

		}

		return p;

	}

	

	public static void main(String[] args)

    {

    	String prestr="ABDGCEFH";

    	String instr="DGBAECHF";

    	if(args.length>1)

    	{

    		prestr=args[0];

    		instr=args[1];

    	}

    	Tree1 t1=new Tree1(prestr,instr);

    	t1.preorderTraversal();

    	t1.inorderTraversal();

    	t1.postorderTraversal();

    }

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值