zoukankan      html  css  js  c++  java
  • POJ(2003)多叉树的基本操作

    //多叉树的建立
    #include<iostream>
    #include<cstdio>
    #include<string>
    #include<list>
    #include<map>
    #include<cstring>
    using namespace std;
    struct node
    {
        string name;//节点的名字
        node* parent;//便于删除
        list<node*> sons;//儿子节点
    };
    map<string,node*> Hash;//很精髓(可以直接寻找到string对应的子树,不用在根据string寻找)  (学到了)
    void hires(const string& s1,const string& s2)//s1 下插入 s2
    {
        node* father = Hash[s1];//找到插入的节点
        node* cur = new node();//创建新的节点
        cur->name = s2;
        cur->parent = father;//更改儿子的节点
        father->sons.push_back(cur);//加入新节点
        Hash[s2] = cur;//往子点中加入节点
    }
    void print(int dep,node* root)//深搜递归调用
    {
        if(!root)
            return;//当前节点为空
        //递归终止
        for(int i=0;i!=dep;++i)
            cout<<'+';//显示递归层数
        cout<<root->name<<endl;//当前递归的name
        for(auto it = root->sons.begin();it != root->sons.end();++it)
        {
            print(dep+1,*it);
        }//深搜递归迭代
    }
    void fire(const string& name)//删除的节点
    {
        node* cur = Hash[name];//找到当前的子树节点
        Hash.erase(name);//从字典中删除
        while(!(cur->sons).empty())//如果它的儿子节点不为空     ==递归删除
        {
            cur->name = cur->sons.front()->name;//变为删除第一个儿子节点
            Hash[cur->name] = cur;//将子树赋给第一个儿子节点
            cur = cur->sons.front();
        }
        //此时cur 节点无儿子
        node* p = cur->parent;//cur parent
        p->sons.remove(cur);//删除节点,相当于节点上移
    }
    int main()
    {
        string str;
        cin>>str;
        node* root = new node();//new 出根节点
        root->name = str;
        Hash[str] = root;//储存root
        string str1,str2;
        while(cin>>str1)
        {
            if(str1=="print")
            {
                print(0,root);
            cout<<"------------------------------------------------------------"<<endl;
            }else if(str1=="fire")
            {
                cin>>str2;
                fire(str2);
            }else{
                cin>>str2;
                cin>>str2;
                hires(str1,str2);
            }
        }
    }
    不怕万人阻挡,只怕自己投降。
  • 相关阅读:
    【c#】无法修改“xxx”的返回值,因为它不是变量
    【c#】在C#中属性不可作为 ref 或 out 参数传递
    【概念】浮点数
    【概念】Winform
    【概念】数据库、服务器、N层架构、.NET、上位机、C/S和B/S、MVC、ADO.NET
    【c#】串口通信汇总
    【总线】UART、Modbus、I2C、SPI、RS232、RS485及串口通讯常用参数
    zookeeper应用场景
    Zookeeper选举(fastleaderelection算法)
    ZAB协议
  • 原文地址:https://www.cnblogs.com/newstartCY/p/11453326.html
Copyright © 2011-2022 走看看