File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ package easy ;
2
+
3
+ public class DiameterOfBinaryTree543 {
4
+ public class TreeNode {
5
+ int val ;
6
+ TreeNode left ;
7
+ TreeNode right ;
8
+
9
+ TreeNode () {
10
+ }
11
+
12
+ TreeNode (int val ) {
13
+ this .val = val ;
14
+ }
15
+
16
+ TreeNode (int val , TreeNode left , TreeNode right ) {
17
+ this .val = val ;
18
+ this .left = left ;
19
+ this .right = right ;
20
+ }
21
+ }
22
+
23
+ int ans = 0 ;
24
+
25
+ public int diameterOfBinaryTree (TreeNode root ) {
26
+ if (root == null )
27
+ return 0 ;
28
+
29
+ if (root .left == null && root .right == null )
30
+ return 0 ;
31
+
32
+ int diameter = height (root .left ) + height (root .right );
33
+ if (diameter > ans )
34
+ ans = diameter ;
35
+
36
+ diameterOfBinaryTree (root .left );
37
+ diameterOfBinaryTree (root .right );
38
+
39
+ return ans ;
40
+ }
41
+
42
+ private int height (TreeNode node ) {
43
+ if (node == null )
44
+ return 0 ;
45
+
46
+ if (node .left == null && node .right == null )
47
+ return 1 ;
48
+
49
+ int lheight = 1 + height (node .left );
50
+ int rheight = 1 + height (node .right );
51
+
52
+ return Math .max (lheight , rheight );
53
+ }
54
+ }
You canβt perform that action at this time.
0 commit comments