简体   繁体   中英

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.)

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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