【问题标题】:How to print if the value inserted in a BST should be inserted in the left or right subtree如果在 BST 中插入的值应插入左子树或右子树,如何打印
【发布时间】:2021-04-06 23:00:20
【问题描述】:

我在 BST 中插入值并打印“left”如果该值应该插入左子树或“right” " 如果值应该插入右子树但是当我要打印时,打印了几个右/左,我该如何解决?我认为这是由于递归,但没有递归我无法解决。

BST 插入代码:

Node *insert(Node **root, int key)
{
    if(*root == NULL)
    {
        Node *newNode = (Node*)malloc(sizeof(Node));
        if(newNode == NULL)
            return NULL;
        newNode->key= key;
        newNode->left = NULL;
        newNode->right = NULL;
        (*root) = newNode; 
        return newNode; 
    }
    if(key < (*root)->key){
        printf("left ");
        return insert(&((*root)->left),key);
    }
    else{
        printf("right ");
        return insert((&(*root)->right),key);
    }
}

示例: 插入值:25 - 20 - 36 - 10 - 22 - 30

【问题讨论】:

    标签: binary-search-tree


    【解决方案1】:

    我从预期的输出中得到的是“左”或“右”表示节点相对于其父节点的相对位置。 如果是这样,您可以这样做:

    if(key < (*root)->key){
        if ( (*root)->left==NULL)
            printf("left ");
        return insert(&((*root)->left),key);
    }
    else{
        if ( (*root)->right==NULL)
               printf("right ");
        return insert((&(*root)->right),key);
    }
    

    逻辑是,我们将在插入步骤前 1 步知道它是左还是右。我刚刚检查了我们要去的下一个节点是否为 NULL。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-06
      相关资源
      最近更新 更多