LC.P1026[节点与其祖先之间的最大差值]

方法一:DFS

通过DFS,记录以该节点为根节点的路径上的最大值与最小值,最后更新答案。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int ans;

public int maxAncestorDiff(TreeNode root) {
dfs(root, root.val, root.val);
return ans;
}

private void dfs(TreeNode node, int max, int min) {
if (node == null) return;
max = Math.max(max, node.val);
min = Math.min(min, node.val);
dfs(node.left, max, min);
dfs(node.right, max, min);
ans = Math.max(ans, max - min);
}
}