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
.
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
.
Example 1:
Input: root = [8,3,10,1,6,null,14,null,null,4,7,13]
Output: 7
Explanation: We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
Example 2:
Input: root = [1,null,2,null,0,3]
Output: 3
Constraints:
- The number of nodes in the tree is in the range
[2, 5000]
. 0 <= Node.val <= 105
這道題給了一棵二叉樹,讓找某個結點和其祖先結點最大的差的絕對值,題目中給了圖很好的說明了兩個結點之間的關系。注意這里並不是任意兩個結點都可以做差取絕對值,必須一個要是另一個的祖先結點,這剛好符合二叉樹的先序遍歷的順序,當遍歷到某個結點的時候,該結點的祖先結點都已經遍歷過了,但是為了找出最大的差絕對值,我們需要記錄當前遍歷過的祖先結點中的最大值和最小值,用它們和當前結點值做差並取絕對值,並分別更新結果 res,所以整個操作就可以直接在遞歸函數中進行了,參見代碼如下:
解法一:
class Solution {
public:
int maxAncestorDiff(TreeNode* root) {
int res = 0;
helper(root, root->val, root->val, res);
return res;
}
void helper(TreeNode* node, int mn, int mx, int& res) {
if (!node) return;
res = max(res, abs(node->val - mn));
res = max(res, abs(mx - node->val));
mn = min(mn, node->val);
mx = max(mx, node->val);
helper(node->left, mn, mx, res);
helper(node->right, mn, mx, res);
}
};
我們也可以寫的更簡潔一下,用子函數的返回值當作結果 res,這樣就少了一個參數了,參見代碼如下:
解法二:
class Solution {
public:
int maxAncestorDiff(TreeNode* root) {
return helper(root, root->val, root->val);
}
int helper(TreeNode* node, int mn, int mx) {
if (!node) return mx - mn;
mn = min(mn, node->val);
mx = max(mx, node->val);
return max(helper(node->left, mn, mx), helper(node->right, mn, mx));
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1026
參考資料:
https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/