-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiameterOfBinaryTree.cpp
More file actions
44 lines (42 loc) · 1.03 KB
/
diameterOfBinaryTree.cpp
File metadata and controls
44 lines (42 loc) · 1.03 KB
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
35
36
37
38
39
40
41
42
43
44
/**
* 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 diameterOfBinaryTree(TreeNode* root) {
if (!root) return 0;
int left = len(root->left);
int right = len(root->right);
int res = left + right;
return max(res,max(diameterOfBinaryTree(root->left),diameterOfBinaryTree(root->right)));
}
int len(TreeNode* root){
int left,right;
if (!root) return 0;
left = len(root->left);
right = len(root->right);
return max(left,right)+1;
}
};
class Solution {
public:
int res = 0;
int diameterOfBinaryTree(TreeNode* root) {
len(root);
return res;
}
int len(TreeNode* root){
int left,right;
if (!root) return 0;
left = len(root->left);
right = len(root->right);
res = max(res,left+right);
return max(left,right)+1;
}
};