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

2024.4.7

      • 题目来源
      • 我的题解
        • [方法一 哈希表+多叉树的前序遍历](#方法一 哈希表+多叉树的前序遍历)

题目来源

力扣每日一题;题序:1600

我的题解

方法一 哈希表+多叉树的前序遍历

发现继承顺序的生成与多叉树的前序遍历一致,只需要在遍历过程中将已经去世的给排除就可以了。

如何存储继承关系?使用哈希表[父亲,儿子集合]

需要额外存储已经过世的人。注:有坑!!!!使用List要超时,只能使用Set
时间复杂度

  • ThroneInheritance(kingName):O(1);
  • birth(parentName, childName):O(1);
  • death(name):O(1);
  • getInheritanceOrder():O(n),其中 n 是当前树中的总人数。需要对整棵树进行一次前序遍历,时间复杂度为 O(n)。
    空间复杂度:O(n)。
java 复制代码
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);
        }
    }
}

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

相关推荐
alphaTao4 小时前
LeetCode 每日一题 2026/2/2-2026/2/8
算法·leetcode
sino爱学习4 小时前
高性能线程池实践:Dubbo EagerThreadPool 设计与应用
java·后端
甄心爱学习4 小时前
【leetcode】判断平衡二叉树
python·算法·leetcode
颜酱4 小时前
从二叉树到衍生结构:5种高频树结构原理+解析
javascript·后端·算法
不知名XL5 小时前
day50 单调栈
数据结构·算法·leetcode
风生u5 小时前
activiti7 详解
java
岁岁种桃花儿5 小时前
SpringCloud从入门到上天:Nacos做微服务注册中心(二)
java·spring cloud·微服务
Word码5 小时前
[C++语法] 继承 (用法详解)
java·jvm·c++
@––––––5 小时前
力扣hot100—系列2-多维动态规划
算法·leetcode·动态规划
TT哇5 小时前
【实习 】银行经理端两个核心功能的开发与修复(银行经理绑定逻辑修复和线下领取扫码功能开发)
java·vue.js