Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 1026. Maximum Difference Between Node and Ancestor

Rain Hu

1026. Maximum Difference Between Node and Ancestor


一、題目

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:
tmp-tree

Example 2: tmp-tree-1

Constraints:


二、分析

三、解題

1. DFS

int res = 0;
int maxAncestorDiff(TreeNode* root) {
    helper(root, root->val, root->val);
    return res;
}
void helper(TreeNode* root, int maxv, int minv) {
    if (!root) return;
    maxv = max(maxv, root->val);
    minv = min(minv, root->val);
    helper(root->left, maxv, minv);
    helper(root->right, maxv, minv);
    res = max(res, maxv-minv);
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 1339. Maximum Product of Splitted Binary Tree
Next
[LeetCode] 872. Leaf-Similar Trees