forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
diameter-of-n-ary-tree.py
53 lines (46 loc) · 1.52 KB
/
diameter-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
# Time: O(n)
# Space: O(h)
# Definition for a Node.
class Node(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children if children is not None else []
class Solution(object):
def diameter(self, root):
"""
:type root: 'Node'
:rtype: int
"""
def iter_dfs(root):
result = [0]*2
stk = [(1, (root, result))]
while stk:
step, params = stk.pop()
if step == 1:
node, ret = params
for child in reversed(node.children):
ret2 = [0]*2
stk.append((2, (ret2, ret)))
stk.append((1, (child, ret2)))
else:
ret2, ret = params
ret[0] = max(ret[0], ret2[0], ret[1]+ret2[1]+1)
ret[1] = max(ret[1], ret2[1]+1)
return result
return iter_dfs(root)[0]
# Time: O(n)
# Space: O(h)
class Solution2(object):
def diameter(self, root):
"""
:type root: 'Node'
:rtype: int
"""
def dfs(node):
max_dia, max_depth = 0, 0
for child in node.children:
child_max_dia, child_max_depth = dfs(child)
max_dia = max(max_dia, child_max_dia, max_depth+child_max_depth+1)
max_depth = max(max_depth, child_max_depth+1)
return max_dia, max_depth
return dfs(root)[0]