Skip to content

Commit

Permalink
Sync LeetCode submission - Maximum Difference Between Node and Ancest…
Browse files Browse the repository at this point in the history
…or (cpp)
  • Loading branch information
pradeeptosarkar committed Jan 11, 2024
1 parent 765806f commit 67f84c4
Showing 1 changed file with 21 additions and 13 deletions.
Original file line number Diff line number Diff line change
@@ -1,17 +1,25 @@
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {

public:

int maxAncestorDiff(TreeNode* root, int maxi=INT_MIN, int mini=INT_MAX) {

if(!root) return(maxi-mini);

maxi=max(maxi, root->val);

mini=min(mini, root->val);

return max(maxAncestorDiff(root->left, maxi, mini), maxAncestorDiff(root->right, maxi, mini));

int maxAncestorDiff(TreeNode* root, int curMin = INT_MAX, int curMax = INT_MIN)
{
if(!root)
return curMax - curMin;

curMin = min(curMin, root -> val);
curMax = max(curMax, root -> val);

return max(maxAncestorDiff(root -> left, curMin, curMax),
maxAncestorDiff(root -> right, curMin, curMax));
}

};

0 comments on commit 67f84c4

Please sign in to comment.