diff --git a/README.md b/README.md index e29ef74..ba30c1c 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/problems/leetcode/1026/solution.js b/problems/leetcode/1026/solution.js new file mode 100644 index 0000000..551e65a --- /dev/null +++ b/problems/leetcode/1026/solution.js @@ -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); + } + +};