-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path543.cpp
More file actions
25 lines (23 loc) · 662 Bytes
/
Copy path543.cpp
File metadata and controls
25 lines (23 loc) · 662 Bytes
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
class Solution {
public:
int maxLen = 0;
int diameterOfBinaryTree(TreeNode *root) {
if (!root)
return 0;
maxLen = 0;
int len = helper(root->left) + helper(root->right);
if (maxLen < len) maxLen = len;
return maxLen;
}
int helper(TreeNode *root) {
if (!root)
return 0;
else if (!root->left && !root->right)
return 1;
int leftLen = helper(root->left);
int rightLen = helper(root->right);
int &&len = leftLen + rightLen;
if (maxLen < len) maxLen = len;
return 1 + (leftLen > rightLen ? leftLen : rightLen);
}
};