【问题标题】:Inserting elements in a BST在 BST 中插入元素
【发布时间】:2018-05-16 00:09:21
【问题描述】:

我试图在 BST 中插入元素但没有得到正确的结果。 我没有打印出所有数组元素,而是只打印了1,11,14 元素而不是整个数组元素。

int arr[10] = { 11, 2, 4, 23, 1, 98, 88, 65, 33, 14 };
void insertNodeinBST(int data,node **root){

    node *new_n = (node*)malloc(sizeof(node));
    new_n->leftChild = new_n->rightChild = NULL;
    new_n->data = data;
      //check if root is null
    if (*root == NULL) {
        *root = new_n;   
    }
    else if (data < (*root)->data){
        //if data is less than current root's data add it to left child
        insertNodeinBST(data, &(*root)->leftChild);
        (*root)->leftChild = new_n;
    }
    else {
      //if data is more than current root's data add it to right child
        insertNodeinBST(data, &(*root)->rightChild);   
        (*root)->rightChild = new_n;
    }

}

//print BST 
void printInorder(node *root){

        if (root == NULL)
            return;

        /* first recur on left child */
        printInorder(root->leftChild);

        /* then print the data of node */
        printf("%d ", root->data);

        /* now recur on right child */
        printInorder(root->rightChild);

}

int _tmain(int argc, _TCHAR* argv[])
{

    int i = 0;
    node *root = NULL;
    for (i = 0; i < 10; i++){
        //inserting nodes
        insertNodeinBST(arr[i], &root);
    }
    printInorder(root);
    return 0;
}

请让我知道我在这里缺少什么。

【问题讨论】:

    标签: c data-structures binary-search-tree


    【解决方案1】:

    你几乎已经完成了,只是insertNodeinBST() 中的几件事:

    你应该只在root是NULL时才创建新节点,否则你每次访问一个新节点时都要不断创建一个新节点,寻找插入的地方:

    //check if root is null
    if (*root == NULL) {
        node *new_n = (node*)malloc(sizeof(node));
        new_n->leftChild = new_n->rightChild = NULL;
        new_n->data = data;
    
        *root = new_n;
    }
    

    上面的代码负责插入新节点,所以你不需要其他的分配,改变:

    } else if (data < (*root)->data) {
        //if data is less than current root's data add it to left child
        insertNodeinBST(data, &(*root)->leftChild);
        (*root)->leftChild = new_n;
    } else {
        //if data is more than current root's data add it to right child
        insertNodeinBST(data, &(*root)->rightChild);
        (*root)->rightChild = new_n;
    }
    

    到

    } else if (data < (*root)->data) {
        //if data is less than current root's data add it to left child
        insertNodeinBST(data, &(*root)->leftChild);
    } else {
        //if data is more than current root's data add it to right child
        insertNodeinBST(data, &(*root)->rightChild);
    }
    

    递归调用将在到达正确的空节点时将指针设置为新节点。

    【讨论】:

    • 不客气。您可能还想研究返回节点指针的递归 BST 插入节点函数,我认为它看起来比修改 node * 参数的这个更干净。如果您有兴趣,请告诉我,我会挖掘我的版本并发布给您。
    • 我确实找到了在谷歌上返回节点指针的解决方案。但我想有目的地更新根指针以更好地理解指针。尽管我同意您的观点,但返回节点指针的解决方案要干净得多。谢谢!
    猜你喜欢
    • 2021-10-03
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多