forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
maximum-difference-between-node-and-ancestor.py
52 lines (46 loc) · 1.38 KB
/
maximum-difference-between-node-and-ancestor.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
# Time: O(n)
# Space: O(h)
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# iterative stack solution
class Solution(object):
def maxAncestorDiff(self, root):
"""
:type root: TreeNode
:rtype: int
"""
result = 0
stack = [(root, 0, float("inf"))]
while stack:
node, mx, mn = stack.pop()
if not node:
continue
result = max(result, mx-node.val, node.val-mn)
mx = max(mx, node.val)
mn = min(mn, node.val)
stack.append((node.left, mx, mn))
stack.append((node.right, mx, mn))
return result
# Time: O(n)
# Space: O(h)
# recursive solution
class Solution2(object):
def maxAncestorDiff(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def maxAncestorDiffHelper(node, mx, mn):
if not node:
return 0
result = max(mx-node.val, node.val-mn)
mx = max(mx, node.val)
mn = min(mn, node.val)
result = max(result, maxAncestorDiffHelper(node.left, mx, mn))
result = max(result, maxAncestorDiffHelper(node.right, mx, mn))
return result
return maxAncestorDiffHelper(root, 0, float("inf"))