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