Skip to content

Commit 681509c

Browse files
committed
add mdbn question
1 parent 4df129f commit 681509c

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {TreeNode} root
11+
* @return {number}
12+
*/
13+
14+
// Time O(n) where n is the number of nodes
15+
// Space O(n)
16+
var maxAncestorDiff = function (root) {
17+
if (root === null) return;
18+
return helper(root, root.val, root.val);
19+
};
20+
21+
function helper(node, currMax, currMin) {
22+
if (node === null) {
23+
return currMax - currMin;
24+
} else {
25+
currMax = Math.max(currMax, node.val);
26+
currMin = Math.min(currMin, node.val);
27+
const left = helper(node.left, currMax, currMin);
28+
const right = helper(node.right, currMax, currMin);
29+
return Math.max(left, right);
30+
}
31+
}

0 commit comments

Comments
 (0)