-3
我編寫了一個函數來刪除二叉搜索樹中的一個節點。 這是我的代碼。爲什麼局部變量自動改變
#include <iostream>
struct BSTNode
{
int data;
BSTNode *left;
BSTNode *right;
};
BSTNode * GetNode(int data);
BSTNode * FindMin(BSTNode *root);
BSTNode * Insert(BSTNode *root, int data);
void PreOrder(BSTNode *root);
BSTNode * DeleteNode(BSTNode *root,int data);
BSTNode * GetNode(int data)
{
BSTNode *newNode = new BSTNode;
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
BSTNode * FindMin(BSTNode *root)
{
if(root == NULL)
return root;
while(root->left != NULL)
root = root->left;
return root;
}
BSTNode * Insert(BSTNode *root, int data)
{
if(root == NULL)
{
root = GetNode(data);
return root;
}
else if (data <= root->data)
root->left = Insert(root->left, data);
else if (data > root->data)
root->right = Insert(root->right, data);
return root;
}
void PreOrder(BSTNode *root)
{
if(root == NULL)
return;
std::cout << root->data << std::endl;
PreOrder(root->left);
PreOrder(root->right);
}
BSTNode * DeleteNode(BSTNode *root,int data)
{
if(root == NULL)
return root;
else if(data < root->data)
root->left = DeleteNode(root->left, data);
else if(data > root->data)
root->right = DeleteNode(root->right, data);
else // Found the Node
{
// case 1: No child
if(root->left == NULL && root->right == NULL)
{
delete root;
root = NULL;
return root;
}
// case 2: One child
else if(root->left == NULL)
{
BSTNode * temp = root;
root = root->right;
delete temp;
return root;
}
else if(root->right = NULL)
{
BSTNode * temp = root;
root = root->left;
delete temp;
return root;
}
else // case 3: two child
{
BSTNode * temp = FindMin(root->right);
root->data = temp->data;
root->right = DeleteNode(root->right, temp->data);
}
}
}
int main()
{
BSTNode *root = NULL;
root = Insert(root, 15);
root = Insert(root, 10);
root = Insert(root, 20);
root = Insert(root, 25);
root = Insert(root, 8);
root = Insert(root, 12);
root = DeleteNode(root, 15);
PreOrder(root);
return 0;
}
,但我遇到一個問題,
else // case 3: two child
{
BSTNode * temp = FindMin(root->right);
root->data = temp->data;
root->right = DeleteNode(root->right, temp->data);
}
程序時來到else語句,根 - >右鍵成爲NULL自動
爲什麼出現這種情況?我該如何解決它?
任何想法讚賞!
'else if(root-> right = NULL)'oops。 'DeleteNode'並不總是返回任何東西。打開你的編譯器警告! – user657267
我真不小心!謝謝。 – Superxy