Skip to content

1026. Maximum Difference Between Node and Ancestor 👍

  • Time: $O(n)$
  • Space: $O(h)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int maxAncestorDiff(TreeNode* root) {
    return maxAncestorDiff(root, root->val, root->val);
  }

 private:
  // return |max - min| of the tree w/ root
  int maxAncestorDiff(TreeNode* root, int mini, int maxi) {
    if (!root)
      return 0;

    mini = min(mini, root->val);
    maxi = max(maxi, root->val);
    const int l = maxAncestorDiff(root->left, mini, maxi);
    const int r = maxAncestorDiff(root->right, mini, maxi);
    return max({maxi - mini, l, r});
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int maxAncestorDiff(TreeNode root) {
    return maxAncestorDiff(root, root.val, root.val);
  }

  // return |max - min| of the tree w/ root
  private int maxAncestorDiff(TreeNode root, int min, int max) {
    if (root == null)
      return 0;

    min = Math.min(min, root.val);
    max = Math.max(max, root.val);
    final int l = maxAncestorDiff(root.left, min, max);
    final int r = maxAncestorDiff(root.right, min, max);
    return Math.max(max - min, Math.max(l, r));
  }
}