LeetCode 1130. Minimum Cost Tree From Leaf Values解题报告(python)

本文介绍了一种使用递归方法解决LeetCode上关于二叉树的问题,即寻找两个节点A和B,其中A是B的祖先,且两节点值之差的最大值。通过递归记录左右子树的最大最小值,最终找到满足条件的最大差值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1130. Minimum Cost Tree From Leaf Values

  1. 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值