1600. Throne Inheritance

39 阅读1分钟

image.png

Solution: N-tree pre order traversal

image.png

  • 「else return x's oldest child who's not in curOrder」-> pick a child node and do dfs;

  • 「else return Successor(x's parent, curOrder)」-> finished exploring subtree rooted at x, then traverse parent

  • 「 if x is the king return null」-> we have expolred the entire tree

class ThroneInheritance {
    Map<String, List<String>> tree;
    Set<String> dead;
    List<String> res;
    String king;

    public ThroneInheritance(String kingName) {
        tree = new HashMap<>();
        dead = new HashSet<>();
       
        king = kingName;
    }
    
    public void birth(String parentName, String childName) {
        List<String> children = tree.getOrDefault(parentName, new ArrayList<>());
        children.add(childName);
        tree.put(parentName, children);
    }
    
    public void death(String name) {
        dead.add(name);
    }
    
    public List<String> getInheritanceOrder() {
        res = new ArrayList<>();
        dfs(king);
        return res;
    }

    // Pre order traversal
    public void dfs(String name) {
        if (!dead.contains(name)) {
            res.add(name);
        }

        // for nodes without children, assign a default empty list
        List<String> children = tree.getOrDefault(name, new ArrayList<>());

        for (String child : children) {
            dfs(child);
        }
    }
}