[英]Delete node from BST in C
我試圖了解此功能是在線創建的,用於從BST刪除節點。 有些事情我聽不懂
這是代碼:
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類型,是否應該使用雙指針?
對於第一個問題,您應該正確: if(data < root->data)
。 對於第二個問題,不完全是。 您顯然應該定義一個指針頭,它是樹的頭,並創建一個將數據插入到bst的函數,因此該函數執行malloc。 您在主程序中需要做的所有事情就是在開始時將頭指針初始化為NULL,因此它應類似於:
int main(){
struct Node *tree=NULL;
int number=...;
...
input_to_bst(&tree,number);
...
new_tree= Delete(tree,24);
還要注意,新樹不需要malloc,因為您的函數返回一個已經顯示給結構的指針,而您要做的是new_tree也將指向該結構。
對於您的最后一個問題,是的,您當然可以傳遞雙指針(實際上,我在input_to_bst(&tree);
的定義中遵循了這種方式)。
函數input_to_bst定義的示例可以是:
void input_to_bst(treeptr* head,int number){
if((*head)==NULL){
(*head)=(treeptr)malloc(sizeof(struct tree));
(*head)->data=number;
(*head)->left=NULL;
(*head)->right=NULL;
}
else{
if(((*head)->data)>number) input_to_bst(&((*head)->left),number);
else (((*head)->data)<number) input_to_bst(&((*head)->right),number);
}
}
我們假設已經定義了結構:
struct tree{
int data;
struct tree* right;
struct tree* left;
};
typedef struct tree* treeptr;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.