我编写了一个删除二叉搜索树中节点的函数。 这是我的代码。
#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语句时,root-&gt; right自动变为NULL
为什么会这样?我该如何解决?
任何想法都赞赏!
答案 0 :(得分:0)
在您的代码中,您在检查以下代码时犯了一些拼写错误
else if(root->right = NULL)
{
BSTNode * temp = root;
root = root->left;
delete temp;
return root;
}
以上行else if(root->right = NULL)
应为root->right == NULL
,但您写为root->Right = NULL
。