C中的二进制搜索树实现 - 错误插入

时间:2017-01-25 04:24:51

标签: c binary-search-tree

我试图在C中实现二进制搜索树。我的插入方法无法正常工作。这个的有序印刷是:

  

1 2 4 3 5 7 6 10

预购印刷品是:

  

5 3 2 1 4 7 10 6

订购后的印刷品是:

  

1 4 2 3 6 10 7 5

我试图摆弄那些不那么大的东西,然后和'#34;左边"和"对" char数组我用来标记下一步的每个输入,但到目前为止我什么都没有。我将不胜感激。非常感谢你!

    int main(int argc, const char * argv[]) {

        struct node* root1 = (struct node*)malloc(sizeof(struct node));
        root1->value = 5;
        root1->left = NULL;
        root1->right = NULL;
        root1->parent = NULL;
        insert(3, root1);
        insert(2, root1);
        insert(1, root1);
        insert(7, root1);
        insert(10, root1);
        insert(6, root1);
        insert(4, root1);
    }

    //Does an initial comparison to set up the helper function 'H' to actually insert the value.
    void insert(int val, struct node* rootNode) {
        if (val < (rootNode)->value) {
            insertH(val, rootNode, "left");
        } else if (val > (rootNode)->value) {
            insertH(val, rootNode, "right");
        }
    }

    //Inserts val into the BST in its proper location
    void insertH(int val, struct node* rootNode, char* helper) {
    if (!strcmp(helper, "left")) {
        if (rootNode->left == NULL) {
            rootNode->left = (struct node*)malloc(sizeof(struct node));
            rootNode->left->value = val;
            (rootNode->left)->parent = rootNode;
            rootNode->left->left = NULL;
            rootNode->left->right = NULL;
        } else {
            if (val < (rootNode)->value) {
                insertH(val, rootNode->left, "left");
            } else if (val > (rootNode)->value) {
                insertH(val, rootNode->left, "right");
            }
        }
    } else if (!strcmp(helper, "right")) {
        if (rootNode->right == NULL) {
            rootNode->right = (struct node*)malloc(sizeof(struct node));
            rootNode->right->value = val;
            (rootNode->right)->parent = rootNode;
            rootNode->right->left = NULL;
            rootNode->right->right = NULL;

        } else {
            if (val < (rootNode)->value) {
                insertH(val, rootNode->right, "left");
            } else if (val > (rootNode)->value) {
                insertH(val, rootNode->right, "right");
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

在BST中,始终在叶子处插入新密钥。我们开始从根搜索一个密钥,直到我们到达一个叶节点。找到叶节点后,新节点将添加为叶节点的子节点 这是带有注释的代码,您可以了解其工作原理,希望您能找到这个有用的

/* A utility function to insert a new node with given key in BST */
struct node* insert(struct node* node, int key)
{
    /* If the tree is empty, return a new node */
    if (node == NULL) return newNode(key);

    /* Otherwise, recur down the tree */
    if (key < node->key)
        node->left  = insert(node->left, key);
    else if (key > node->key)
        node->right = insert(node->right, key);   

    /* return the (unchanged) node pointer */
    return node;
}