字典树删除多余的结点疑问

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <string>
#include <iostream>
using namespace std;

struct node {
    int cnt;//记录个数;
    struct node *next[26];
    node()
    {
        cnt=0;
        memset(next,NULL,sizeof(next));
    }
};

void buildtrie(node *root,string s)//建树;
{
    node *p=root;
    node *tmp=NULL;
    int l=s.size();
    for(int i=0;i<l;i++)
    {
        if(p->next[s[i]-'A']==NULL)
        {
            tmp=new node;
            p->next[s[i]-'A']=tmp;
        }
        p=p->next[s[i]-'A'];
    }
    p->cnt++;
}

void findtrie(node *root ,string s)//查询
{
    node *p=root;
    int l=s.size();
    for(int i=0;i<l;i++)
    {
        p=p->next[s[i]-'A'];
    }
    printf("%d\n",p->cnt-1);
}

void del(node *root)//为什么root值永远为main函数传过来的值,递归的时候也是这个值,并且只执行一次,这是我调试的得到结果,但是删除结点代码就是这样,提交对了,但不知道为什么。调试也不懂,懂得可以给我讲下,///万分感谢
{
    for(int i=0;i<26;i++)
        if(root->next[i])
            del(root->next[i]);
    delete(root);
}

int main()
{
    int n;
    string s;
    node root;
    scanf("%d",&n);
    while(n--)
    {
        cin >> s;
        sort(s.begin(),s.end());
        buildtrie(&root,s);
        findtrie(&root,s);
        del(&root);
    }
    return 0;
}

 

posted on 2016-05-17 11:28  青春的梦想付诸行动  阅读(212)  评论(1编辑  收藏  举报

导航