Skip to content

Commit 7c41b2d

Browse files
committed
Time: 3 ms (85.41%), Space: 10.1 MB (59.95%) - LeetHub
1 parent 205f22f commit 7c41b2d

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
15+
int helper(TreeNode* root, int currMax, int currMin)
16+
{
17+
if(!root)
18+
return currMax - currMin;
19+
currMax = max(currMax,root->val);
20+
currMin = min(currMin,root->val);
21+
22+
int left = helper(root->left,currMax,currMin);
23+
int right = helper(root->right,currMax,currMin);
24+
25+
return max(left,right);
26+
}
27+
28+
29+
int maxAncestorDiff(TreeNode* root) {
30+
31+
if(!root)
32+
return 0;
33+
34+
return helper(root,root->val,root->val);
35+
36+
37+
}
38+
};

0 commit comments

Comments
 (0)