-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiameterOfBinaryTree.java
More file actions
31 lines (30 loc) · 1.22 KB
/
Copy pathDiameterOfBinaryTree.java
File metadata and controls
31 lines (30 loc) · 1.22 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
//https://leetcode.com/problems/diameter-of-binary-tree/
public class DiameterOfBinaryTree {
//Intially I thought adding left depth and right depth at root would solve as always root adds more diameter
// but for the case where root diameter formed at root can be less than diameter formed at subtree having same depth, hence maintain a global maxDiameter variable to update maxDia every time and return depth
int maxDia=0;
public int diameterOfBinaryTree(TreeNode root) {
int maxDep=0;
int leftDep=dfs(root.left);
int rightDep=dfs(root.right);
maxDia=Math.max(leftDep+rightDep,maxDia);
return maxDia;
}
public int dfs(TreeNode root) {
if(root!=null) {
if(root.left==null && root.right==null) {
return 1;
}
int leftDep =dfs(root.left);
int rightDep=dfs(root.right);
//finding max dep out of both children
int dep =1+Math.max(leftDep,rightDep);
//calculating diameter formed at this node
int dia=leftDep+rightDep;
//updating if this is maxDiameter
maxDia=Math.max(dia,maxDia);
return dep;
}
return 0;
}
}