简体   繁体   English

删除二叉搜索树中的节点

[英]Deleting Node in Binary Search Tree

I have written code to delete a node in Binary Search Tree. 我已经编写了删除二进制搜索树中的节点的代码。 Code : 代码:

#include<iostream>
using namespace std;
struct Node {
    int value; 
    Node* left;
    Node* right;
};
Node* GetNewNode(int data) {
    Node* newNode = new Node();
    newNode->value = data;
    newNode->left = newNode->right = NULL;
    return newNode;
}
void Insert(Node* &root,int x)
{
    if(root==NULL) root=GetNewNode(x);
    else if(x>root->value) Insert(root->right,x);
    else Insert(root->left,x);
}
Node* Search(Node* root,int x) 
{
    if(root->value==x) return root ;
    else if(root->value>x) Search(root->left,x);
    else if(root->value<x) Search(root->right,x);
}
Node* Searchmin(Node* root) 
{
    if(root==NULL) cout<<"Empty tree"<<endl;
    if(root->left==NULL) return root;
    else Searchmin(root->left);
}

void Inorder(Node* root)
{
    if(root==NULL) return;
    else {
        Inorder(root->left);
        cout<<root->value<<endl;
        Inorder(root->right);
    }
}
Node* deleteNode(Node* root, int x)
{
    Node* nodeptr;
    nodeptr=Search(root,x);
    if(nodeptr->left==NULL && nodeptr->right==NULL) return nodeptr;
    else if(nodeptr->left==NULL && nodeptr->right!=NULL)
    {
      nodeptr->value=nodeptr->right->value;
      nodeptr=nodeptr->right;
      return nodeptr;   
    }
    else if(nodeptr->right==NULL && nodeptr->left!=NULL)
    {
      nodeptr->value=nodeptr->left->value;
      nodeptr=nodeptr->left;
      return nodeptr;
    }
    else{
        nodeptr->value=Searchmin(nodeptr->right)->value;
        deleteNode(nodeptr->right,nodeptr->value);
        return nodeptr;}    
}
int main() 
{
    Node* root=NULL;
    Insert(root,20);
    Insert(root,15);
    Insert(root,25);
    Insert(root,10);
    Insert(root,16);
    Insert(root,7);
    Inorder(root);
    Node* x=deleteNode(root,7);
    delete x;
    Inorder(root);
}

Compiler doesn't show any syntax error either. 编译器也不显示任何语法错误。 The program is crashing. 程序崩溃了。 Its not even deleting leaf node. 它甚至没有删除叶节点。 I can't find the error. 我找不到错误。 Please help. 请帮忙。 (These lines are just to extend length of question because stackoverflow was not accepting generating error in question on lines of long code and short description.) (这些行只是为了延长问题的长度,因为stackoverflow不接受在长代码和简短描述的行上产生问题的错误。)

The first thing your delete function does is call search, and what's the first thing search does? 删除功能要做的第一件事是调用搜索,搜索的第一件事是什么?

Node* Search(Node* root,int x) 
{
    if(root->value==x) return root ;

Search immediately dereferences root . 搜索立即取消引用root It never checks for a null pointer. 它从不检查空指针。 This means it's guaranteed your search function will dereference a null pointer if there is no node in the tree to be found. 这意味着如果树中没有找到节点,则可以确保您的搜索功能将取消引用空指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM