LeetCode 题解工作台
节点与其祖先之间的最大差值
给定二叉树的根节点 root ,找出存在于 不同 节点 A 和 B 之间的最大值 V ,其中 V = |A.val - B.val| ,且 A 是 B 的祖先。 (如果 A 的任何子节点之一为 B,或者 A 的任何子节点是 B 的祖先,那么我们认为 A 是 B 的祖先) 示例 1: 输入: root…
3
题型
7
代码语言
3
相关题
当前训练重点
中等 · 二分·树·traversal
答案摘要
对于每个节点,求其与祖先节点的最大差值,我们只需要求出该节点与祖先节点最大值和最小值的差值。取所有节点与祖先节点差值的最大值即可。 因此,我们设计一个函数 $dfs(root, mi, mx)$,表示当前搜索到的节点为 ,其祖先节点的最大值为 ,最小值为 ,函数内更新最大差值 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给定二叉树的根节点 root,找出存在于 不同 节点 A 和 B 之间的最大值 V,其中 V = |A.val - B.val|,且 A 是 B 的祖先。
(如果 A 的任何子节点之一为 B,或者 A 的任何子节点是 B 的祖先,那么我们认为 A 是 B 的祖先)
示例 1:

输入:root = [8,3,10,1,6,null,14,null,null,4,7,13] 输出:7 解释: 我们有大量的节点与其祖先的差值,其中一些如下: |8 - 3| = 5 |3 - 7| = 4 |8 - 1| = 7 |10 - 13| = 3 在所有可能的差值中,最大值 7 由 |8 - 1| = 7 得出。
示例 2:
输入:root = [1,null,2,null,0,3] 输出:3
提示:
- 树中的节点数在
2到5000之间。 0 <= Node.val <= 105
解题思路
方法一:DFS
对于每个节点,求其与祖先节点的最大差值,我们只需要求出该节点与祖先节点最大值和最小值的差值。取所有节点与祖先节点差值的最大值即可。
因此,我们设计一个函数 ,表示当前搜索到的节点为 ,其祖先节点的最大值为 ,最小值为 ,函数内更新最大差值 。
函数 的逻辑如下:
- 若 为空,直接返回。
- 否则,我们更新 。
- 然后更新 , ,并且递归搜索左右子树。
在主函数中,我们调用 ,最后返回 即可。
时间复杂度 ,空间复杂度 。其中 为二叉树节点个数。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:
def dfs(root: Optional[TreeNode], mi: int, mx: int):
if root is None:
return
nonlocal ans
ans = max(ans, abs(mi - root.val), abs(mx - root.val))
mi = min(mi, root.val)
mx = max(mx, root.val)
dfs(root.left, mi, mx)
dfs(root.right, mi, mx)
ans = 0
dfs(root, root.val, root.val)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for a clear understanding of tree traversal and recursive solutions.
- question_mark
Ensure the candidate can explain how state tracking is essential for finding the maximum difference.
- question_mark
Evaluate if the candidate can optimize the solution and explain the trade-offs of space and time complexities.
常见陷阱
外企场景- error
Failing to correctly track both the minimum and maximum values as you traverse down the tree.
- error
Misunderstanding the ancestor relationship, which could lead to incorrect calculations of the node differences.
- error
Not handling edge cases such as very small or unbalanced trees effectively.
进阶变体
外企场景- arrow_right_alt
Finding the maximum difference between nodes for a non-binary tree structure.
- arrow_right_alt
Implementing the solution iteratively without recursion.
- arrow_right_alt
Handling a tree where the node values are all the same, potentially simplifying the problem.