Skip to content

Commit

Permalink
1026. Maximum Difference Between Node and Ancestor.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
keineahnung2345 authored Mar 2, 2020
1 parent 90a124d commit 4415808
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions 1026. Maximum Difference Between Node and Ancestor.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/274610/JavaC%2B%2BPython-Top-Down

//Top Down
//Runtime: 4 ms, faster than 96.94% of C++ online submissions for Maximum Difference Between Node and Ancestor.
//Memory Usage: 11.9 MB, less than 86.36% of C++ online submissions for Maximum Difference Between Node and Ancestor.

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxAncestorDiffMM(TreeNode* node, int mx, int mn){
return node ? max(maxAncestorDiffMM(node->left, max(node->val, mx), min(node->val, mn)),
maxAncestorDiffMM(node->right, max(node->val, mx), min(node->val, mn))): mx-mn;
}

int maxAncestorDiff(TreeNode* root) {
return maxAncestorDiffMM(root, 0, INT_MAX);
}
};

0 comments on commit 4415808

Please sign in to comment.