Skip to content

Commit

Permalink
Leetcode/1026
Browse files Browse the repository at this point in the history
  • Loading branch information
herrera-ignacio committed Jan 11, 2024
1 parent 0b79383 commit 9fd9d4c
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@
- [1089: Duplicate Zeros](problems/leetcode/1089) - Queue
- [1198: Find smallest common element in all rows](problems/leetcode/1198) - Matrix
- [1208: Unique number of occurrences](problems/leetcode/1208) - Set + Map
- [1026: Maximum difference between node and ancestor](problems/leetcode/1026) - Medium - Tree
- [1235: Maximum profit in job scheduling](problems/leetcode/1235) - Dynamic Programming + Binary Search
- [1239: Maximum length of a concatenated string with unique characters](problems/leetcode/1239)
- [1323: Maximum 69 number](problems/leetcode/1323)
Expand Down
46 changes: 46 additions & 0 deletions problems/leetcode/1026/solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxAncestorDiff = function(root) {
let diff = 0;
let min = root.val;
let max = root.val;

if (!root) {
return diff;
}

dfs(root, min, max);

return diff;

function dfs(node, min, max) {
if (!node) {
return;
}

diff = Math.max(
diff,
Math.max(
Math.abs(min - node.val),
Math.abs(max - node.val)
)
);

min = Math.min(min, node.val);
max = Math.max(max, node.val);

dfs(node.left, min, max);
dfs(node.right, min, max);
}

};

0 comments on commit 9fd9d4c

Please sign in to comment.