2012-11-19 142 views
2

这是在BST中找到ceilfloor的代码。当我试图插入数据。每次插入呼叫转到第一个if条件时。即使我通过指针。该值不在主函数中更新。有人能告诉我为什么这样吗?为什么根值没有被更新

using namespace std; 

struct Node 
{ 
    int key; 
    struct Node* right; 
    struct Node* left; 
}; 

struct Node* newNode(int key) 
{ 
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); 
    newNode->right = NULL; 
    newNode->left = NULL; 
    newNode->key = key; 
    return newNode; 
} 


void insert(struct Node** root,int key) { 
    if((*root) == NULL){ 
     (*root)= newNode(key); 
     cout<<"entered first if condition"<<endl; 
    } 
    else if((*root)->key <= key) 
     insert(&((*root)->left),key); 
    else 
     insert (&((*root)->right),key); 
} 

int ceil(struct Node* root , int input) 
{ 
    if (root == NULL) 
    return -1; 
    if(root->key == input) 
    return root->key; 
    if(root->key < input) 
    return ceil(root->right , input); 
    else{ 
    int ceilnum = ceil(root->left, input); 
    return (ceilnum >= input) ? ceilnum : root->key; 
    } 
} 

int main() 
{ 
    int size, temp, ceilfor; 
    struct Node* root = NULL; 
    cout<< "size" << endl; 
    cin >> size; 
    for(int i = 0; i< size; i++) 
    { 
    cin >> temp; 
    insert(&root,temp); 
    } 
    cout<< root->key; 
    cout<< root->left->key; 
    cout << root->right->key; 
    cout << "ceil for" << endl; 
    cin >> ceilfor; 
    cout<< ceil(root, ceilfor) <<endl; 
} 
+0

你可以尝试在'main'和'insert'函数中打印'root'的值吗? –

回答

2

它必须达到第一个条件(直接或间接通过递归调用)。

实际插入仅在第一个if块中发生,其他块将递归地到达第一个if块。

相关问题