C二进制搜索树没有为左右节点分配值?

时间:2015-02-23 23:58:25

标签: c binary-search-tree

我似乎遇到了一个问题,即当我将值分配到我的二叉搜索树中时,root将接收输入的第一个值,但之后不会输入任何其他值。如果我去直接看看root - >左或根 - >对,它只返回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;
}

2 个答案:

答案 0 :(得分:1)

变化:

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

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

同样以相同方式更改左侧版本。现在,您正在分配子节点,但从未将它们分配给右侧或左侧指针。他们基本上被扔掉了。

答案 1 :(得分:0)

非常确定错误是您将新插入的左右节点分配给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都给出了正确的结果。

See this Ideone example