LeetCode 1506 Find root of N-ary tree

we are given List tree as the input, and we are gonna find the root of this N-ary tree. (Pay attention that it says each unique value)
return the root node.

so how can we find the root? we need to find a node that the in degree is 0.
so we use each node and it’s children, then the node that contains in these nodes but not in children node sets.

Based on this idea, we have the following code:

class Solution {
    public Node findRoot(List<Node> tree) {
        if (tree == null || tree.size() == 0) return null;
        
        Set<Node> seen = new HashSet<>();
        
        for (Node node: tree) {
            for (Node child: node.children) {
                seen.add(child);
            }
        }
        
        for (Node node: tree) {
            if (!seen.contains(node)) {
                return node;
            }
        }
        return null;
        
    }
}

the time complexitiy will be the O(N) and the space complexity will be O(N)

follow up:
Could you solve this problem in constant space complexity with a linear time algorithm?
so now we can’t use set, but since all the value of nodes are unique, if we add up all the value of nodes and add up all the children nodes. and then we calculate the difference between them, and we check each node’s value again and check which node value is that.

class Solution {
    public Node findRoot(List<Node> tree) {
        if (tree == null || tree.size() == 0) return null;
        int sumWithRoot = 0;
        int sumWithoutRoot = 0;
        for (Node node: tree) {
            sumWithRoot += node.val;
            for (Node child: node.children) {
                sumWithoutRoot += child.val;
            }
        }
        
        for (Node node: tree) {
            if (node.val == sumWithRoot - sumWithoutRoot) {
                return node;
            }
        }
        return null;
        
    }
}

and there is another interesting idea:
remember what XOR do, if 3 ^ 4 ^ 5 ^ 4 ^ 5, the value will be 3, only left 3
注意 异或运算符满足交换律
因为所有的值都是unqiue的 所以对所有的值进行异或 剩下的就是那个root值
这个代码跟上一个几乎一样 就不写了

posted @ 2020-11-04 22:55  EvanMeetTheWorld  阅读(36)  评论(0)    收藏  举报