1026. Maximum Difference Between Node and Ancestor
Solution
Passing the max/min value during the DFS traversal path
int ret = 0;
public int maxAncestorDiff(TreeNode root) {
dfs(root, root.val, root.val);
return ret;
}
public void dfs(TreeNode node, int max, int min){
if(node == null) return;
ret = Math.max(ret, max - node.val);
ret = Math.max(ret, node.val - min);
if(node.left != null){
dfs(node.left, Math.max(max, node.left.val), Math.min(min, node.left.val));
}
if(node.right != null){
dfs(node.right, Math.max(max, node.right.val), Math.min(min, node.right.val));
}
}
Last updated
Was this helpful?