c - 删除二叉搜索树根节点的问题

标签 c binary-search-tree

我正在尝试从 BST 中删除根节点,然后按顺序打印树。根删除似乎是一个问题,所有其他节点都已成功删除。

根号是 20。

订单打印 5 6 7 8 9 10 17 18 20 23 24 25 29 55 56 57 58 59

提供要删除的节点

20

删除后

5 6 7 8 9 10 17 18 20 5 6 7 8 9 10 17 18 23 24 25 29 55 56 57 58 59

正如您所见,删除后,二叉树与预期不符。粗体键是不需要的。 下面是我的代码

void treeDeleteNode (binTreeT **tree, binTreeT *node)
{
    binTreeT *succs;
    binTreeT *parent;
    binTreeT *root = *tree;

    if (node->rchild == NULL) {
        transplantTree (&root, node, node->lchild);
    }
    else if (node->lchild == NULL) {
        transplantTree (&root, node, node->rchild);
    }
    else {
        succs = treeMin (node->rchild);
        parent = getParentNode (root, succs);
        if (parent != node) {
            transplantTree (&root, succs, succs->rchild);
            succs->rchild = node->rchild;
        }
        transplantTree (&root, node, succs);
        succs->lchild = node->lchild;
    }
}


void transplantTree (binTreeT **root, binTreeT *old, binTreeT *new)
{
    binTreeT *rootRef = *root;
    binTreeT *parent;

    parent = getParentNode(rootRef, old);
    if (NULL == parent) {
        *root = new;
    }
    else {
        if (parent->lchild == old) {
            parent->lchild = new;
        }
        else {
            parent->rchild = new;
        }
    }
}


binTreeT* treeMin (binTreeT *tree)
{
    while (tree->lchild != NULL) {
        tree = tree->lchild;
    }
    return tree;
}


binTreeT* getParentNode(binTreeT *root, binTreeT* node)
{
    binTreeT *parent = NULL;

    while (root->data != node->data) {
        parent = root;
        if (node->data < root->data) {
            root = root->lchild;
        }
        else if(node->data > root->data) {
            root = root->rchild;
        }
    }
    return parent;
}


void inOrderPrint (binTreeT *tree)
{
    if (NULL != tree) {
        inOrderPrint (tree->lchild);
        printf("%d \t", tree->data);
        inOrderPrint (tree->rchild);
    }
}

......任何帮助表示赞赏......

最佳答案

在函数 treeDeleteNode 中,每次调用 transplantTree 函数时,都应该将它的 tree 作为第一个参数传递,而不是 &root >。这是因为根节点可以在此函数中修改,并且这些更改应该对 tree 变量本身进行。

关于c - 删除二叉搜索树根节点的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17501314/

相关文章:

c - 库之间的区别以及如何包含它们

c++ - Windows命令提示符中的彩色文本一行

if-statement - 如果否则赋值 "move out of borrowed content"

data-structures - 将非重叠范围映射到值的数据结构?

c++ - 在 C/C++ 中使用单个初始化来初始化具有相同值的多个指针

c - 在另一个函数中使用输入的值

c - 如何在 Char 指针中连接变量和文字

c - C中的红黑树实现

algorithm - 构建二叉搜索树和 AVL 树所需的时间复杂度之间的差异?

java - 在java中的二叉树递归函数中存储计数器