почему корневое значение не обновляется

Это код для поиска ceil а также floor в BST. Когда я пытаюсь вставить данные. каждый раз, когда вызов вставки переходит к первому условию 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;
}

2

Решение

Он должен прийти к первому условию (прямо или косвенно через рекурсивные вызовы).

Фактическая вставка происходит только в первом if блок и другие блоки будут рекурсивно достигать первого if блок.

2

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector