1026. Maximum Difference Between Node and Ancestor
Last updated
Last updated
/**
* Time complexity : O(N) since we visit all nodes once.
* Space complexity : O(N) since we need stacks to do recursion, and the
* maximum depth of the recursion is the height of the tree, which is O(N)
* in the worst case and O(log(N)) in the best case.
*/
class Solution {
public int maxAncestorDiff(TreeNode root) {
if(root == null) {
return 0;
}
return dfs(root, root.val, root.val);
}
private int dfs(TreeNode node, int min, int max) {
if(node == null) {
return max-min;
}
if(node.val < min) {
min = node.val;
}
if(node.val > max) {
max = node.val;
}
return Math.max(dfs(node.left, min, max), dfs(node.right, min, max));
}
}