将二叉树转换为线程二叉树的问题

时间:2018-12-29 02:17:09

标签: c# binary-tree binary-search-tree

我想将二叉树转换为线程二叉树。 这是我要转换的算法和代码。 但我收到错误消息“ System.StackOverflowException类型的异常”。 “

   public void ConvertToTBT(Node r, int[] inorder)
    {
        for (int i = 0; i < inorder.Length; i++)
        {
            Node temp = Search(r, inorder[i]);

            if (i <= inorder.Length - 2)
                if (temp.rightChild == null)
                {
                    temp.rightChild = Search(r, inorder[i + 1]);
                    temp.is_right_thread = true;
                }
            if (i != 0)
                if (temp.leftChild == null)
                {
                    temp.leftChild = Search(r, inorder[i - 1]);
                    temp.is_left_thread = true;
                }

        }
    }

这是我在这里找到并在我的代码中使用的搜索方法(找到一个节点并返回该节点)

public Node Search(Node root, int data)
    {
        if (root != null)
        {
            if (root.data == data)
                return root;
            else
            {
                Node foundNode = Search(root.leftChild, data);
                if (foundNode == null)
                    foundNode = Search(root.rightChild, data);
                return foundNode;
            }
        }
        else
            return null;
    }

我在哪里犯错?!

如果您有将BT转换为TBT的更好的主意,那么请帮助我!

请注意,我的树是二叉树,而不是二叉树

也是我的biuldTree方法

public Node BuildTree(int[] inorder, int[] preorder, int instart, int inend)
    {
        if (instart > inend)
            return null;
        if (preindex >= inorder.Length)
            return null;
        int pickedpre = preorder[preindex];
        preindex++;

        Node newnode = new Node(pickedpre);
        if (instart == inend)
            return newnode;

        for (int i = 0; i < inorder.Length; i++)
        {
            if (inorder[i] == pickedpre)
            {
                inindex = i;
                break;
            }
        }
        newnode.leftChild = BuildTree(inorder, preorder, instart, inindex - 1);
        newnode.rightChild = BuildTree(inorder, preorder, inindex + 1, inend);

        root = newnode;
        return newnode;
    }

0 个答案:

没有答案
相关问题