码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-05-17 13:09:45      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

#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;
}

 

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

标签:

原文地址:http://www.cnblogs.com/WDKER/p/5500866.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!