forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
diameter-of-binary-tree.py
55 lines (48 loc) · 1.53 KB
/
diameter-of-binary-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
# Time: O(n)
# Space: O(h)
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def iter_dfs(node):
result = 0
max_depth = [0]
stk = [(1, [node, max_depth])]
while stk:
step, params = stk.pop()
if step == 1:
node, ret = params
if not node:
continue
ret1, ret2 = [0], [0]
stk.append((2, [node, ret1, ret2, ret]))
stk.append((1, [node.right, ret2]))
stk.append((1, [node.left, ret1]))
elif step == 2:
node, ret1, ret2, ret = params
result = max(result, ret1[0]+ret2[0])
ret[0] = 1+max(ret1[0], ret2[0])
return result
return iter_dfs(root)
# Time: O(n)
# Space: O(h)
class Solution2(object):
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(root):
if not root:
return 0, 0
left_d, left_h = dfs(root.left)
right_d, right_h = dfs(root.right)
return max(left_d, right_d, left_h+right_h), 1+max(left_h, right_h)
return dfs(root)[0]