Skip to content

Commit d00e4c3

Browse files
committed
new soln
1 parent 9a1323c commit d00e4c3

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

1026.MaxAncestorDiff.cs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// 1026. Maximum Difference Between Node and Ancestor
2+
// Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b.
3+
// A node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b.
4+
5+
// Example 1:
6+
// Input: root = [8,3,10,1,6,null,14,null,null,4,7,13]
7+
// Output: 7
8+
// Explanation: We have various ancestor-node differences, some of which are given below :
9+
// |8 - 3| = 5
10+
// |3 - 7| = 4
11+
// |8 - 1| = 7
12+
// |10 - 13| = 3
13+
// Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
14+
// Example 2:
15+
// Input: root = [1,null,2,null,0,3]
16+
// Output: 3
17+
/**
18+
* Definition for a binary tree node.
19+
* public class TreeNode {
20+
* public int val;
21+
* public TreeNode left;
22+
* public TreeNode right;
23+
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
24+
* this.val = val;
25+
* this.left = left;
26+
* this.right = right;
27+
* }
28+
* }
29+
*/
30+
public class Solution {
31+
public int MaxAncestorDiff(TreeNode root) {
32+
return MaxDiff(root, root.val, root.val);
33+
}
34+
public int MaxDiff(TreeNode root, int max, int min){
35+
if(root == null)
36+
return 0;
37+
int res = Math.Max(
38+
Math.Abs(max-root.val),
39+
Math.Abs(min-root.val));
40+
max = Math.Max(max, root.val);
41+
min = Math.Min(min, root.val);
42+
return Math.Max( res,
43+
Math.Max(MaxDiff(root.left, max, min),
44+
MaxDiff(root.right, max, min)));
45+
}
46+
47+
}

0 commit comments

Comments
 (0)