-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1026.maximum-difference-between-node-and-ancestor.java
More file actions
43 lines (42 loc) · 1.18 KB
/
Copy path1026.maximum-difference-between-node-and-ancestor.java
File metadata and controls
43 lines (42 loc) · 1.18 KB
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
33
34
35
36
37
38
39
40
41
42
43
/**
* 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 maxdiff;
public int maxAncestorDiff(TreeNode root) {
if (null == root) return 0;
maxdiff = 0;
dfs(root, root.val, root.val);
return maxdiff;
}
public void dfs(TreeNode root, int min, int max) {
if (root == null) return;
/**
* Compute the difference with the root
* */
int diff1 = Math.abs(root.val - min);
int diff2 = Math.abs(root.val - max);
/**
* find the max difference from those value
* */
maxdiff = Math.max(maxdiff, diff1);
maxdiff = Math.max(maxdiff, diff2);
/**
* do dfs in both trees
* */
dfs(root.left, Math.min(min, root.val), Math.max(max, root.val));
dfs(root.right, Math.min(min, root.val), Math.max(max, root.val));
}
}