@@ -22,7 +22,7 @@ public class TreeNode {
22
22
23
23
int ans = 0 ;
24
24
25
- public int diameterOfBinaryTree (TreeNode root ) {
25
+ public int diameterOfBinaryTree1 (TreeNode root ) {
26
26
if (root == null )
27
27
return 0 ;
28
28
@@ -33,8 +33,8 @@ public int diameterOfBinaryTree(TreeNode root) {
33
33
if (diameter > ans )
34
34
ans = diameter ;
35
35
36
- diameterOfBinaryTree (root .left );
37
- diameterOfBinaryTree (root .right );
36
+ diameterOfBinaryTree1 (root .left );
37
+ diameterOfBinaryTree1 (root .right );
38
38
39
39
return ans ;
40
40
}
@@ -51,4 +51,31 @@ private int height(TreeNode node) {
51
51
52
52
return Math .max (lheight , rheight );
53
53
}
54
+
55
+ private int height1 (TreeNode node ) {
56
+ if (node == null )
57
+ return -1 ;
58
+
59
+ int lheight = height1 (node .left );
60
+ int rheight = height1 (node .right );
61
+
62
+ return Math .max (lheight , rheight ) + 1 ;
63
+ }
64
+
65
+ public int diameterOfBinaryTree (TreeNode root ) {
66
+ if (root == null )
67
+ return 0 ;
68
+ // max distance between two nodes of LHS
69
+ int leftDia = diameterOfBinaryTree (root .left );
70
+ // max distance between two nodes of RHS
71
+ int rightDia = diameterOfBinaryTree (root .right );
72
+
73
+ // diameter that passes through the root node
74
+ int rootWayDia = height1 (root .left ) + height1 (root .right ) + 2 ;
75
+
76
+ int dia = Math .max (rootWayDia , Math .max (leftDia , rightDia ));
77
+
78
+ return dia ;
79
+ }
80
+
54
81
}
0 commit comments