Skip to content

Commit 692aeaa

Browse files
authored
Create DiameterBinaryTree.cpp
1 parent 4c9e481 commit 692aeaa

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

DiameterBinaryTree.cpp

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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+
int height(TreeNode*root){
15+
if(root==NULL){
16+
return 0;
17+
}
18+
return max(height(root->left),height(root->right))+1;
19+
}
20+
int diameterOfBinaryTree(TreeNode* root) {
21+
if(root==NULL){
22+
return 0;
23+
}
24+
int dia=height(root->left)+height(root->right);
25+
int leftDia=diameterOfBinaryTree(root->left);
26+
int rightDia=diameterOfBinaryTree(root->right);
27+
int ans=max(leftDia,rightDia);
28+
ans=max(ans,dia);
29+
return ans;
30+
}
31+
};

0 commit comments

Comments
 (0)