在C的二叉搜索树中插入新节点

时间:2018-06-05 12:30:49

标签: c binary-search-tree nodes

我已经有了一个包含5个级别的二叉搜索树,我正在尝试创建一个插入新节点但我无法正常工作的函数。如何编辑我的代码以进行插入?

TREE *insertion(TREE *root, int num){
    TREE *node, *new_node;
    node = root;
    new_node=(TREE *)malloc(sizeof(TREE));
    new_node->rec = num;
    new_node->lp = NULL;
    new_node->rp = NULL;

    while(node != NULL ){
//      if(node->rec == num){
//          printf("This value exists\n");
//          return NULL;            
//      }
        if(num > node->rec){
            node = node->rp;    
        }
        else
            node = node->lp;
    }

    if(num>node->rec)
        node = new_node;
    else
        node = new_node;

    return root;}

1 个答案:

答案 0 :(得分:0)

如果num > node->rec为真,您需要检查node->rp是否为NULL,而您未检查。

同时将head地址传递给insertion(),以便传递的变量head中的修改会影响调用函数,而您无需返回任何内容。< / p>

假设您正在调用insertion(),如下所示

int main(void) {
        TREE *head = NULL;
        insertion(&head,10);/* pass the  address of head so that modification will affect here also otherwise just passing head means it will treat as call by value */
        insertion(&head,5);
        insertion(&head,15);
        return 0;
}

insertion()函数看起来像

int  insertion(TREE **root, int num) {
        TREE *node, *new_node;
        node = *root;
        new_node = malloc(sizeof(TREE)); /* no need of casting malloc() results */
        new_node->rec = num;
        new_node->lp = NULL;
        new_node->rp = NULL;

        while(node != NULL ){
                if(node->rec == num){
                        printf("This value exists\n");
                        return NULL;`
                }

                if(num > node->rec){ /* right child of root node */
                        if(node->rp != NULL) { /* check node->rp is empty or not
                                                  if not, update node.. check here itself */
                                node = node->rp; /* update node */
                        }
                        else {
                                node->rp = new_node; /* insert new node */
                                return; /* new node added at correct position , so no need of any further processing, jut return */
                        }
                }
                else {
                        if(node->lp != NULL) {
                                node = node->lp;
                        }
                        else {
                                node->lp = new_node;
                                return;
                        }
                }
        }
}