Maximum Difference Between Node and Ancestor LeetCode solution in Java

1
/**
2
* Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode
3
* right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left,
4
* TreeNode right) { this.val = val; this.left = left; this.right = right; } }
5
*/
6
class Solution {
7
public int maxAncestorDiff(TreeNode root) {
8

9
if (root == null) return 0;
10

11
return find(root, Integer.MAX_VALUE, Integer.MIN_VALUE);
12
}
13

14
public int find(TreeNode root, int min, int max) {
15
if (root == null) return Math.abs(max - min);
16

17
min = Math.min(min, root.val);
18
max = Math.max(max, root.val);
19

20
return Math.max(find(root.left, min, max), find(root.right, min, max));
21
}
22
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0