|
| 1 | +# Time: O(n) |
| 2 | +# Space: O(h) |
| 3 | + |
| 4 | +# Definition for a Node. |
| 5 | +class Node(object): |
| 6 | + def __init__(self, val=None, children=None): |
| 7 | + self.val = val |
| 8 | + self.children = children if children is not None else [] |
| 9 | + |
| 10 | + |
| 11 | +class Solution(object): |
| 12 | + def diameter(self, root): |
| 13 | + """ |
| 14 | + :type root: 'Node' |
| 15 | + :rtype: int |
| 16 | + """ |
| 17 | + def iter_dfs(root): |
| 18 | + result = [0]*2 |
| 19 | + stk = [(1, (root, result))] |
| 20 | + while stk: |
| 21 | + step, params = stk.pop() |
| 22 | + if step == 1: |
| 23 | + node, ret = params |
| 24 | + for child in reversed(node.children): |
| 25 | + ret2 = [0]*2 |
| 26 | + stk.append((2, (ret2, ret))) |
| 27 | + stk.append((1, (child, ret2))) |
| 28 | + else: |
| 29 | + ret2, ret = params |
| 30 | + ret[0] = max(ret[0], ret2[0], ret[1]+ret2[1]+1) |
| 31 | + ret[1] = max(ret[1], ret2[1]+1) |
| 32 | + return result |
| 33 | + |
| 34 | + return iter_dfs(root)[0] |
| 35 | + |
| 36 | + |
| 37 | +# Time: O(n) |
| 38 | +# Space: O(h) |
| 39 | +class Solution2(object): |
| 40 | + def diameter(self, root): |
| 41 | + """ |
| 42 | + :type root: 'Node' |
| 43 | + :rtype: int |
| 44 | + """ |
| 45 | + def dfs(node): |
| 46 | + max_dia, max_depth = 0, 0 |
| 47 | + for child in node.children: |
| 48 | + child_max_dia, child_max_depth = dfs(child) |
| 49 | + max_dia = max(max_dia, child_max_dia, max_depth+child_max_depth+1) |
| 50 | + max_depth = max(max_depth, child_max_depth+1) |
| 51 | + return max_dia, max_depth |
| 52 | + |
| 53 | + return dfs(root)[0] |
0 commit comments