Skip to content

Commit fa2d45f

Browse files
Solution of day 18-q1 in cpp #396
1 parent 8cbe42e commit fa2d45f

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
## Approach:
2+
<br /> 1. Using dfs find the max value node and min value node in each branch and calculate their diffence.
3+
<br /> 2. Return the max difference.
4+
## Code:
5+
```
6+
/**
7+
* Definition for a binary tree node.
8+
* struct TreeNode {
9+
* int val;
10+
* TreeNode *left;
11+
* TreeNode *right;
12+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
13+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
14+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
15+
* };
16+
*/
17+
class Solution {
18+
public:
19+
int maxAncestorDiff(TreeNode* root) {
20+
return dfs(root,root->val,root->val);
21+
}
22+
int dfs(TreeNode* root,int mini,int maxx){
23+
if (root==NULL){
24+
return maxx-mini;
25+
}
26+
mini = std::min(mini, root->val);
27+
maxx = std::max(maxx, root->val);
28+
int left_diff = dfs(root->left, mini, maxx);
29+
int right_diff = dfs(root->right, mini, maxx);
30+
return std::max(left_diff, right_diff);
31+
}
32+
};
33+
```

0 commit comments

Comments
 (0)