Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
maximum-difference-between-node-and-ancestor.py 1.38 KB
一键复制 编辑 原始数据 按行查看 历史
# 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"))
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助