-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDiameter.java
27 lines (23 loc) · 867 Bytes
/
Diameter.java
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
/*https://practice.geeksforgeeks.org/problems/diameter-of-binary-tree/1*/
class Solution {
int maxDepth = 0;
int diameter(Node root) {
maxDepth = 0;
checkDepth(root);
return maxDepth-1; //return maxDepth for gfg submission
}
int checkDepth(Node root)
{
//base case
if (root == null)
return 0;
//find the depth of left and right subtrees
int leftSubtreeDepth = checkDepth(root.left);
int rightSubtreeDepth = checkDepth(root.right);
//if the path length is greater than maximum length, update it
if (leftSubtreeDepth+rightSubtreeDepth+1 > maxDepth)
maxDepth = leftSubtreeDepth+rightSubtreeDepth+1;
//return the maximum of two depths
return leftSubtreeDepth > rightSubtreeDepth ? leftSubtreeDepth+1 : rightSubtreeDepth+1;
}
}