FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
LeetCode/DiameterOfBinaryTree.java at master · Orio77/LeetCode · GitHub
Orio77
/
LeetCode
Public
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
LeetCode
/
DiameterOfBinaryTree.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
76 lines (69 loc) · 2.12 KB
Breadcrumbs
LeetCode
/
DiameterOfBinaryTree.java
Copy path
File metadata and controls
76 lines (69 loc) · 2.12 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
// My Take
class
MySolution
{
public
int
diameterOfBinaryTree
(
TreeNode
root
) {
return
(
root
==
null
) ?
0
:
diameterOfBinaryTreeHelper
(
root
,
1
);
}
private
int
diameterOfBinaryTreeHelper
(
TreeNode
node
,
int
level
) {
int
maxDepthLeft
=
0
;
int
maxDepthRight
=
0
;
int
diameter
=
0
;
if
(
node
.
left
!=
null
) {
maxDepthLeft
=
maxDepth
(
node
.
left
,
level
+
1
);
}
if
(
node
.
right
!=
null
) {
maxDepthRight
=
maxDepth
(
node
.
right
,
level
+
1
);
}
if
(
maxDepthLeft
==
0
||
maxDepthRight
==
0
) {
diameter
=
maxDepthLeft
+
maxDepthRight
-
1
;
}
else
diameter
=
maxDepthLeft
+
maxDepthRight
-
2
;
return
Math
.
max
(
diameter
,
Math
.
max
(
diameterOfBinaryTree
(
node
.
right
),
diameterOfBinaryTree
(
node
.
left
)));
}
public
int
maxDepth
(
TreeNode
node
,
int
level
) {
int
maxLeft
=
0
;
int
maxRight
=
0
;
if
(
node
.
left
!=
null
) {
maxLeft
=
maxDepth
(
node
.
left
,
level
+
1
);
}
else
if
(
node
.
right
!=
null
) {
maxRight
=
maxDepth
(
node
.
right
,
level
+
1
);
}
return
(
maxLeft
==
0
&&
maxRight
==
0
) ?
level
:
Math
.
max
(
maxLeft
,
maxRight
);
}
}
// Solution
class
Solution
{
public
int
diameterOfBinaryTree
(
TreeNode
root
) {
if
(
root
==
null
) {
return
0
;
}
int
[]
diameter
=
new
int
[
1
];
maxDepth
(
root
,
diameter
);
return
diameter
[
0
];
}
private
int
maxDepth
(
TreeNode
node
,
int
[]
diameter
) {
if
(
node
==
null
) {
return
0
;
}
int
left
=
maxDepth
(
node
.
left
,
diameter
);
int
right
=
maxDepth
(
node
.
right
,
diameter
);
diameter
[
0
] =
Math
.
max
(
diameter
[
0
],
left
+
right
);
return
Math
.
max
(
left
,
right
)+
1
;
}
}
Back
|
FazBrowse Home
|
New Git URL