1、题干
给定二叉树的根节点 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
2、思路
递归求子孙节点的最小值与最大值,分别求最大值最小值与当前节点值的差的绝对值,比较得出最大差值。
3、代码
function maxAncestorDiff(root: TreeNode | null): number {
let ans = -Infinity;
function dfs(node: TreeNode) {
if (!node) return [Infinity, -Infinity];
if (!node.left && !node.right) return [node.val, node.val];
const r1 = dfs(node.left);
const r2 = dfs(node.right);
const min = Math.min(r1[0], r2[0]);
const max = Math.max(r1[1], r2[1]);
ans = Math.max(ans, Math.abs(node.val - min), Math.abs(node.val - max));
return [Math.min(min, node.val), Math.max(max, node.val)];
}
return dfs(root), ans;
};
4、复杂度
- 时间复杂度:
- 空间复杂度: