-
Notifications
You must be signed in to change notification settings - Fork 6
/
0543.cpp
34 lines (27 loc) · 858 Bytes
/
0543.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* 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 recur(TreeNode* root, int& max_val){
if(!root)
return 0;
int count_l = recur(root->left, max_val);
int count_r = recur(root->right, max_val);
max_val = max(max_val, count_l + count_r);
return max(count_l, count_r) + 1;
}
int diameterOfBinaryTree(TreeNode* root) {
int result = 0;
recur(root, result);
return result;
}
};