根据先序及中序遍历结果创建树,java实现

仓促写完的,初步测试时正确的,还不确定有没有bug,记录一下。

class BinaryTree

{
    public int data;
    public BinaryTree lChild;
    public BinaryTree rChild;
}

public class CreateTree
{
    public static void postTraverse(BinaryTree bTree)
    {
    if (bTree.lChild == null && bTree.rChild == null)
    {
        System.out.println(bTree.data);
        return;
    }
    if (bTree.lChild != null)
    {
        postTraverse(bTree.lChild);
    }
    if (bTree.rChild != null)
    {
        postTraverse(bTree.rChild);
    }
    System.out.println(bTree.data);
    }

    public static BinaryTree createTree(int[] preArray, int[] inArray)
    {
    if (preArray != null && preArray.length == 1)
    {
        int value = preArray[0];
        BinaryTree node = new BinaryTree();
        node.data = value;
        node.lChild = null;
        node.rChild = null;
        return node;
    }
    if (preArray == null)
    {
        return null;
    }
    int rootValue = preArray[0];
    BinaryTree rootNode = new BinaryTree();
    rootNode.data = rootValue;
    int i;
    for (i = 0; i < inArray.length; ++i)
    {
        if (rootValue == inArray[i])
        {
        break;
        }
    }
    int lLength = i;
    int rLength = preArray.length - 1 - lLength;
    int[] lPreArray = null;
    int[] lInArray = null;
    int[] rPreArray = null;
    int[] rInArray = null;
    if (lLength > 0)
    {
        lPreArray = new int[lLength];
        lInArray = new int[lLength];
        for (int j = 0; j < lLength; ++j)
        {
        lPreArray[j] = preArray[j + 1];
        lInArray[j] = inArray[j];
        }
    }
    else if (lLength == 0)
    {
        rootNode.lChild = null;
    }

    if (rLength > 0)
    {
        rPreArray = new int[rLength];
        rInArray = new int[rLength];
        for (int j = 0; j < rLength; ++j)
        {
        int originIndex = j + 1 + i;
        rPreArray[j] = preArray[originIndex];
        rInArray[j] = inArray[originIndex];
        }
    }
    else if (rLength == 0)
    {
        rootNode.rChild = null;
    }

    rootNode.lChild = createTree(lPreArray, lInArray);
    rootNode.rChild = createTree(rPreArray, rInArray);
    return rootNode;
    }

    public static void main(String[] args)
    {
    int[] preArray =
    { 1, 2, 4, 7, 3, 5, 6, 8 };
    int[] inArray =
    { 4, 7, 2, 1, 5, 3, 8, 6 };
    BinaryTree bTree = createTree(preArray, inArray);
    postTraverse(bTree);
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值