-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1026-MaxDiffBetweenNode&Ancestor.java
More file actions
41 lines (35 loc) · 1023 Bytes
/
1026-MaxDiffBetweenNode&Ancestor.java
File metadata and controls
41 lines (35 loc) · 1023 Bytes
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
//Question Link - https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/description/
/**
* 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 res = Integer.MIN_VALUE;
public void diff(TreeNode node, int min, int max){
//store the ancestor diff in min/max
min = Math.min(min, node.val);
max = Math.max(max, node.val);
res = Math.max(res, max-min);
if(node.left != null) {
diff(node.left, min, max);
}
if(node.right != null) {
diff(node.right, min, max);
}
}
public int maxAncestorDiff(TreeNode root) {
diff(root, root.val, root.val);
return res;
}
}