当前位置: 代码网 > it编程>数据库>MsSqlserver > 2024.4.7力扣每日一题——王位继承顺序

2024.4.7力扣每日一题——王位继承顺序

2024年07月28日 MsSqlserver 我要评论
2024.4.7 力扣每日一题 王位继承顺序 哈希表 设计 多叉树的前序遍历

题目来源

力扣每日一题;题序:1600

我的题解

方法一 哈希表+多叉树的前序遍历
class throneinheritance {
    map<string,list<string>> parent;
    set<string> hasdead;
    string king;
    public throneinheritance(string kingname) {
        king=kingname;
        parent=new hashmap<>();
        hasdead=new hashset<>();
    }
    
    public void birth(string parentname, string childname) {
        if(!hasdead.contains(parentname)){
            list<string> l=parent.getordefault(parentname,new arraylist<>());
            l.add(childname);
            parent.put(parentname,l);
        }
    }
    
    public void death(string name) {
        hasdead.add(name);
    }
    
    public list<string> getinheritanceorder() {
        list<string> res=new arraylist<>();
        dfs(king,res);
        return res;
    }
    public void dfs(string p,list<string> res){
        if(!hasdead.contains(p))
            res.add(p);
        for(string s:parent.getordefault(p,new arraylist<>())){
            dfs(s,res);
        }
    }
}

有任何问题,欢迎评论区交流,欢迎评论区提供其它解题思路(代码),也可以点个赞支持一下作者哈😄~

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com