forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
find-root-of-n-ary-tree.py
56 lines (49 loc) · 1.24 KB
/
find-root-of-n-ary-tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# Time: O(n)
# Space: O(1)
# Definition for a Node.
class Node(object):
def __init__(self, val=None, children=None):
pass
class Solution(object):
def findRoot(self, tree):
"""
:type tree: List['Node']
:rtype: 'Node'
"""
root = 0
for node in tree:
root ^= id(node)
for child in node.children:
root ^= id(child)
for node in tree:
if id(node) == root:
return node
return None
class Solution2(object):
def findRoot(self, tree):
"""
:type tree: List['Node']
:rtype: 'Node'
"""
root = 0
for node in tree:
root ^= node.val
for child in node.children:
root ^= child.val
for node in tree:
if node.val == root:
return node
return None
class Solution3(object):
def findRoot(self, tree):
"""
:type tree: List['Node']
:rtype: 'Node'
"""
root = 0
for node in tree:
root += node.val-sum(child.val for child in node.children)
for node in tree:
if node.val == root:
return node
return None