LeetCode Solutions

1026. Maximum Difference Between Node and Ancestor

Time: $O(n)$

Space: $O(h)$

			

class Solution {
 public:
  int maxAncestorDiff(TreeNode* root) {
    return maxAncestorDiff(root, root->val, root->val);
  }

 private:
  // Returns |max - min| of the tree w/ root
  int maxAncestorDiff(TreeNode* root, int mini, int maxi) {
    if (root == nullptr)
      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});
  }
};
			

class Solution {
  public int maxAncestorDiff(TreeNode root) {
    return maxAncestorDiff(root, root.val, root.val);
  }

  // Returns |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));
  }
}