在BST中插入元素

时间:2018-05-16 00:09:21

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

我正在尝试在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;
}

请告诉我这里缺少的东西。

1 个答案:

答案 0 :(得分:1)

你几乎拥有它,只有insertNodeinBST()中的几件事:

您应该只在rootNULL时创建新节点,否则,每次访问新节点时都会继续创建新节点,寻找要插入的位置:

//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);
}

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