簡體   English   中英

C二叉搜索樹沒有為左節點和右節點分配值?

[英]C Binary search tree not assigning values to left and right nodes?

我似乎遇到一個問題,當我向二進制搜索樹中分配值時,根將接受輸入的第一個值,但之后再不輸入其他任何值。 如果我直接查看root-> left或root-> right,它只會返回null。 我凝視了這么久,以至於不知所措。 我確定遞歸確實存在一些基本錯誤,但是我看不到它。 看到我在哪里出錯了,我將不勝感激。

#include <stdio.h>
#include <stdlib.h>
#include "Bst.h"


int main(int argc, char** argv) {
    int value;
    TreeNode* root = NULL;
    printf ("Enter an integer\n");
    scanf ("%d", &value);
    while (value > 0) {
        root = insert (value, root);
        printf ("Enter an integer\n");
        scanf ("%d", &value);    
    }

    printf("The inorder traversal of the tree\n");
    inOrder(root);
    printf("\n");

    printf("The preorder traversal of the tree\n");
    preOrder(root);
    printf("\n");
    return (EXIT_SUCCESS);
}



TreeNode* insert(int newValue, TreeNode* root) {
    TreeNode* temp = NULL;

    //Sets a value to the root
    if (root == NULL) {
        temp = (TreeNode*)malloc(sizeof(TreeNode));
        temp -> value = newValue;
        temp -> left = NULL;
        temp -> right = NULL;
        return temp;
    }

    //Will put a larger value to the right within the tree
    else if (newValue > (root -> value)) {
        temp = insert(newValue, (root -> right));
    }

    //Will put a smaller value to the left
    else {
        temp = insert (newValue, (root -> left));
    }
    return root;
}

void inOrder(TreeNode* root){
    if(root == NULL){
        return;
    }
    else {
        inOrder(root -> left);
        printf("%d", root -> value);
        printf(" ");
        inOrder(root -> right);
    }
    return;
}

void preOrder(TreeNode* root){
    if(root == NULL) {
        return;
    } else {
        preOrder(root -> right);
        printf("%d", root -> value);
        printf(" ");
        preOrder(root -> left);
    }
    return;
}

更改:

temp = insert(newValue, (root -> right));

root->right = insert(newValue, (root -> right));

同樣,以相同方式更改左側版本。 現在,您正在分配子節點,但從未將它們分配給右或左指針。 他們本質上被扔掉了。

可以肯定的是,錯誤是您將新插入的左右節點分配給temp而不是root->rightroot->left ,這會使它們懸在樹外。

更改這些行:

//Will put a larger value to the right within the tree
else if (newValue > (root -> value)){
    temp = insert(newValue, (root -> right));
}

//Will put a smaller value to the left
else{
    temp = insert (newValue, (root -> left));
}

對此:

//Will put a larger value to the right within the tree
    else if (newValue > (root -> value)) {
        root->right = insert(newValue, (root -> right));
    }

//Will put a smaller value to the left
    else {
        root->left = insert (newValue, (root -> left));
    }

此更改使您的代碼在我測試時可以按預期工作; inOrder和preOrder都給出了正確的結果。

請參閱此Ideone示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM