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++;
}
}
}
括号表示法创建二叉树(递归实现)
最新推荐文章于 2024-05-02 01:51:41 发布