我试图理解这个在线建立的函数,用于从BST中删除一个节点。有些事情我无法理解从BST中删除节点C
这是代码:
struct Node* Delete(struct Node *root, int data) {
if (root == NULL) {
return NULL;
}
if (data > root->data) { // data is in the left sub tree.
root->left = Delete(root->left, data);
} else if (data > root->data) { // data is in the right sub tree.
root->right = Delete(root->right, data);
} else {
// case 1: no children
if (root->left == NULL && root->right == NULL) {
delete(root); // wipe out the memory, in C, use free function
root = NULL;
}
// case 2: one child (right)
else if (root->left == NULL) {
struct Node *temp = root; // save current node as a backup
root = root->right;
delete temp;
}
// case 3: one child (left)
else if (root->right == NULL) {
struct Node *temp = root; // save current node as a backup
root = root->left;
delete temp;
}
// case 4: two children
else {
struct Node *temp = FindMin(root->right); // find minimal value of right sub tree
root->data = temp->data; // duplicate the node
root->right = Delete(root->right, temp->data); // delete the duplicate node
}
}
return root; // parent node can update reference
}
问题:
1)为什么它是
if (data > root->data) { // data is in the left sub tree.
root->left = Delete(root->left, data);
它不应该是if(data < root->data)
? (同样的两行代码之后)
2)函数返回一个指向节点的指针,这是否意味着在主函数中我必须做这样的事情?
int main(){
struct Node *tree=malloc(sizeof(Node));
...
struct Node *new_tree=malloc(sizeof(Node));
new_tree= Delete(tree,24);
因此函数代替老树新树,而无需与VAL 24节点?如果我想的函数void类型,我应该使用双指针?