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
class Solution {
 public:
  int maxAncestorDiff(TreeNode* root) {
    return maxAncestorDiff(root, root->val, root->val);
  }

 private:
  // Returns |the maximum - the minimum| of the tree.
  int maxAncestorDiff(TreeNode* root, int mn, int mx) {
    if (root == nullptr)
      return 0;
    mn = min(mn, root->val);
    mx = max(mx, root->val);
    const int l = maxAncestorDiff(root->left, mn, mx);
    const int r = maxAncestorDiff(root->right, mn, mx);
    return max({mx - mn, l, r});
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int maxAncestorDiff(TreeNode root) {
    return maxAncestorDiff(root, root.val, root.val);
  }

  // Returns |the maximum - the minimum| of the tree.
  private int maxAncestorDiff(TreeNode root, int mn, int mx) {
    if (root == null)
      return 0;
    mn = Math.min(mn, root.val);
    mx = Math.max(mx, root.val);
    final int l = maxAncestorDiff(root.left, mn, mx);
    final int r = maxAncestorDiff(root.right, mn, mx);
    return Math.max(mx - mn, Math.max(l, r));
  }
}