-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path543-Diameter-of-Binary-Tree.cpp
38 lines (35 loc) · 1.2 KB
/
543-Diameter-of-Binary-Tree.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
35
36
37
38
class Solution {
public:
// int maxDia = 0;
// int levels(TreeNode* root){
// if(root==NULL) return 0;
// return 1 + max(levels(root->left) , levels(root->right));
// }
// int diameterOfBinaryTree(TreeNode* root) {
// if(root == NULL) return 0;
// int Dia = levels(root->left) + levels(root->right);
// maxDia = max(maxDia , Dia);
// diameterOfBinaryTree(root->left);
// diameterOfBinaryTree(root->right);
// return maxDia;
// }
// Interviwer doesn't like using global variable in the code
// so this code was used
// helper fn and maxDia as reference are used to remove the use of global varriable
int levels(TreeNode* root){
if(root==NULL) return 0;
return 1 + max(levels(root->left) , levels(root->right));
}
void helper(TreeNode* root , int &maxDia){
if(root == NULL) return;
int Dia = levels(root->left) + levels(root->right);
maxDia = max(maxDia , Dia);
helper(root->left , maxDia);
helper(root->right , maxDia);
}
int diameterOfBinaryTree(TreeNode* root) {
int maxDia = 0;
helper(root , maxDia);
return maxDia;
}
};