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

来源:互联网 发布:私人淘宝3c认证怎么弄 编辑:程序博客网 时间:2024/06/11 09:35

仓促写完的,初步测试时正确的,还不确定有没有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);
    }

}
原创粉丝点击