GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

I am trying to delete a node from trie but I am not able to do that so please can anyone suggest changes in my code

#include <iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
struct trienode
{
    struct trienode *child[26];
    bool isLeaf;
};
struct trienode *getNode()
{
    struct trienode *newnode=(struct trienode*)malloc(sizeof(struct trienode));
    newnode->isLeaf=false;
    for(int i=0; i<26; i++)
        newnode->child[i]=NULL;
    return newnode;
}
void insert(struct trienode *root,char *key)
{
    int l=strlen(key);
    int index;
    struct trienode *temp=root;
    for(int i=0; i<l; i++)
    {
        index=key[i]-'a';
        if(temp->child[index]==NULL)
            temp->child[index]=getNode();
        temp=temp->child[index];
    }
    temp->isLeaf=true;
}
int search(char *key,struct trienode *root)
{
    int n=strlen(key);
    struct trienode *temp=root;
    for(int i=0; i<n; i++)
    {
        int index=key[i]-'a';
        if(temp->child[index]==NULL)
            return 0;
        temp=temp->child[index];
    }
    if(temp->isLeaf==true)
        return 1;
    return 0;
}
int isEmpty(struct trienode *p)
{
    for(int i=0; i<26; i++)
    {
        if(p->child[i]!=NULL)
            return 0;
    }
    return 1;
}
void remove(char *key,struct trienode *root,int index,int n)
{
    if(root==NULL)
        return;
    if(index==n)
    {
        if(root->isLeaf)
        {
        root->isLeaf=false;
    if(isEmpty(root))
        delete[] root;
    return;
        }
    }
    int c=key[index]-'a';
    remove(key,root->child[c],index+1,n);
}
int main() {
    struct trienode *root=getNode();
    char key[][100]={"abcd","abc","efg","sumit"};
    for(int i=0; i<=3; i++)
        insert(root,key[i]);
    cout<<search("sumit",root)<<"\n";
    cout<<search("abcd",root)<<"\n";
    cout<<search("abc",root)<<"\n";
    cout<<search("efg",root)<<"\n";
    cout<<search("rachit",root)<<"\n";
    cout<<search("ab",root)<<"\n";
    remove("abcd",root,0,3);
    cout<<search("abc",root)<<"\n";
    cout<<search("abcd",root)<<"\n";
    return 0;
}

asked Jul 20, 2016 by Sumit Kapoor
...