java已知先序中序序列构造二叉树

package demoFive;
/*
*@author:张文波
*@time2020年4月18日上午10:22:33
*/
//已知二叉树前序和中序序列,求二叉树

public class BuildTree
{

    public static String xian="ABC";
    public static String zhong="BAC";
    public static int pos=0;
    public static void main(String[] args)
    {
        node n=createTree(zhong);
        System.out.println("创建成功");
        NodePrint(n);

    }
    // 遍历链表
        public static void NodePrint(node n)
        {
            while (n == null)
            {
                return;
            }
            
            System.out.println(n.data);
            NodePrint(n.getLeft());
            NodePrint(n.getRight());
            
        }
    //创建二叉树
    public static node createTree(String zhong) {
        if(zhong.length()<=0||pos>xian.length()) {
            pos--;
            return null;
        }
        
        node n=new node();
        n.setData(xian.charAt(pos));
        int site=0; 
        //匹配字符
        for(int i=0;i<zhong.length();i++) {
            String temp=zhong.substring(i,i+1);
            if(temp.equals(String.valueOf(xian.charAt(pos)))) {
                site=i;
                break;
            };
        }
        pos++;
        n.setLeft(createTree(zhong.substring(0,site)));
        pos++;
        n.setRight(createTree(zhong.substring(site+1,zhong.length())));
        return n;
        
    }

}
class node{
    char data;
    node left;
    node right;
    public char getData()
    {
        return data;
    }
    public void setData(char data)
    {
        this.data = data;
    }
    public node getLeft()
    {
        return left;
    }
    public void setLeft(node left)
    {
        this.left = left;
    }
    public node getRight()
    {
        return right;
    }
    public void setRight(node right)
    {
        this.right = right;
    }
    
}
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值