|
| 1 | +# 1026. Maximum Difference Between Node and Ancestor |
| 2 | + |
| 3 | +- Difficulty: Medium. |
| 4 | +- Related Topics: Tree, Depth-First Search, Binary Tree. |
| 5 | +- Similar Questions: . |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +Given the ```root``` of a binary tree, find the maximum value ```v``` for which there exist **different** nodes ```a``` and ```b``` where ```v = |a.val - b.val|``` and ```a``` is an ancestor of ```b```. |
| 10 | + |
| 11 | +A node ```a``` is an ancestor of ```b``` if either: any child of ```a``` is equal to ```b``` or any child of ```a``` is an ancestor of ```b```. |
| 12 | + |
| 13 | + |
| 14 | +Example 1: |
| 15 | + |
| 16 | + |
| 17 | + |
| 18 | +``` |
| 19 | +Input: root = [8,3,10,1,6,null,14,null,null,4,7,13] |
| 20 | +Output: 7 |
| 21 | +Explanation: We have various ancestor-node differences, some of which are given below : |
| 22 | +|8 - 3| = 5 |
| 23 | +|3 - 7| = 4 |
| 24 | +|8 - 1| = 7 |
| 25 | +|10 - 13| = 3 |
| 26 | +Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7. |
| 27 | +``` |
| 28 | + |
| 29 | +Example 2: |
| 30 | + |
| 31 | + |
| 32 | + |
| 33 | +``` |
| 34 | +Input: root = [1,null,2,null,0,3] |
| 35 | +Output: 3 |
| 36 | +``` |
| 37 | + |
| 38 | + |
| 39 | +**Constraints:** |
| 40 | + |
| 41 | + |
| 42 | + |
| 43 | +- The number of nodes in the tree is in the range ```[2, 5000]```. |
| 44 | + |
| 45 | +- ```0 <= Node.val <= 105``` |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | +## Solution |
| 50 | + |
| 51 | +```javascript |
| 52 | +/** |
| 53 | + * Definition for a binary tree node. |
| 54 | + * function TreeNode(val, left, right) { |
| 55 | + * this.val = (val===undefined ? 0 : val) |
| 56 | + * this.left = (left===undefined ? null : left) |
| 57 | + * this.right = (right===undefined ? null : right) |
| 58 | + * } |
| 59 | + */ |
| 60 | +/** |
| 61 | + * @param {TreeNode} root |
| 62 | + * @return {number} |
| 63 | + */ |
| 64 | +var maxAncestorDiff = function(root) { |
| 65 | + return helper(root.val, root.val, root); |
| 66 | +}; |
| 67 | + |
| 68 | +var helper = function(max, min, node) { |
| 69 | + if (!node) return 0; |
| 70 | + var newMax = node.val > max ? node.val : max; |
| 71 | + var newMin = node.val < min ? node.val : min; |
| 72 | + return Math.max( |
| 73 | + Math.abs(max - node.val), |
| 74 | + Math.abs(min - node.val), |
| 75 | + node.left ? helper(newMax, newMin, node.left) : 0, |
| 76 | + node.right ? helper(newMax, newMin, node.right) : 0, |
| 77 | + ); |
| 78 | +}; |
| 79 | +``` |
| 80 | + |
| 81 | +**Explain:** |
| 82 | + |
| 83 | +use dfs to visit every node in the tree, carry the maximum and minimum number all the way down, the result should be |max - node.val| or |min - node.val| |
| 84 | + |
| 85 | +**Complexity:** |
| 86 | + |
| 87 | +* Time complexity : O(n). |
| 88 | +* Space complexity : O(n). |
0 commit comments