括号表示法创建二叉树(递归实现)

public class Tree {
	treeNode root;
	int location=0;
	public Tree()
	{
		root=new treeNode();
	}
	public void preorder(treeNode fa)
	{
		System.out.print(fa.data);
		if(fa.left!=null)
			preorder(fa.left);
		if(fa.right!=null)
			preorder(fa.right);
	}
	public void inorder(treeNode fa)
	{
		if(fa.left!=null)
			inorder(fa.left);
		System.out.print(fa.data);
		if(fa.right!=null)
			inorder(fa.right);
	}
	public void postorder(treeNode fa)
	{
		if(fa.left!=null)
			postorder(fa.left);
		if(fa.right!=null)
			postorder(fa.right);
		System.out.print(fa.data);
	}
	public void levelorder(treeNode fa)
	{
		if(fa==root)
			System.out.print(fa.data);
		if(fa.left!=null)
			System.out.print(fa.left.data);
		if(fa.right!=null)
			System.out.print(fa.right.data);
		if(fa.left!=null)
			levelorder(fa.left);
		if(fa.right!=null)
			levelorder(fa.right);
	}
	public void create(String s,treeNode fa)
	{
		if(location==0)
		{
			fa.data=s.charAt(location++);
			location++;//跳过左括号
		}
		treeNode l=new treeNode();
		treeNode r=new treeNode();
		while(location<s.length()&&s.charAt(location)!=',')
		{
			if('A'<=s.charAt(location)&&s.charAt(location)<='Z')
			{
				l.data=s.charAt(location);
				fa.left=l;
			}
			if(s.charAt(location)=='(')
			{
				location++;//跳过左括号
				create(s,l);
			}
			location++;
		}
		while(location<s.length()&&s.charAt(location)!=')')
		{
			if('A'<=s.charAt(location)&&s.charAt(location)<='Z')
			{
				r.data=s.charAt(location);
				fa.right=r;
			}
			if(s.charAt(location)=='(')
			{
				location++;//跳过左括号
				create(s,r);
			}
			location++;
		}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值