1130. Minimum Cost Tree From Leaf Values
- Minimum Cost Tree From Leaf Values python solution
题目描述
Given the root of a binary tree, find the maximum value V for which there exists different nodes A and B where V = |A.val - B.val| and A is an ancestor of B.
(A node A is an ancestor of B if either: any child of A is equal to B, or any child of A is an ancestor of B.)

解析
还是要采用递归的思想解题。将最大最小值沿左右子树记录下去。
class Solution:
def maxAncestorDiff(self, root: TreeNode) -> int:
premin=float('inf')
premax=float('-inf')
self.res=0
def helper(root,maxnum,minnum):
if not root:return
curmax=max(maxnum,root.val)
curmin=min(minnum,root.val)
self.res=max(self.res,abs(curmax-curmin))
helper(root.left,curmax,curmin)
helper(root.right,curmax,curmin)
helper(root, premax, premin)
return self.res
Reference
https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/284129/Python-direct-DFS-solution-beats-99-easy-to-understand
本文介绍了一种使用递归方法解决LeetCode上关于二叉树的问题,即寻找两个节点A和B,其中A是B的祖先,且两节点值之差的最大值。通过递归记录左右子树的最大最小值,最终找到满足条件的最大差值。

628

被折叠的 条评论
为什么被折叠?



