FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode/java/501_Find_Mode_in_Binary_Search_Tree.java at master · jakehoare/leetcode · GitHub
jakehoare
/
leetcode
Public
Notifications
You must be signed in to change notification settings
Fork
30
Star
51
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
/
java
/
501_Find_Mode_in_Binary_Search_Tree.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
67 lines (52 loc) · 1.82 KB
Breadcrumbs
leetcode
/
java
/
501_Find_Mode_in_Binary_Search_Tree.java
Copy path
File metadata and controls
67 lines (52 loc) · 1.82 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
/*
https://leetcode.com/problems/find-mode-in-binary-search-tree/
Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the
given BST. Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than or equal to the node's key.
The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
Both the left and right subtrees must also be binary search trees.
Inorder traversal visits nodes in increasing order. Find length of longest sequence of same val. Repeat inorder
traversal finding all vals with maxFreq.
Time - O(n)
Space - O(1), alternatively Morris traversal avoids recursion
*/
class
Solution
{
private
int
current
=
0
;
private
int
freq
=
0
;
private
int
maxFreq
=
0
;
private
List
<
Integer
>
modes
=
new
ArrayList
<
Integer
>();
private
void
findGreatestFrequency
(
TreeNode
node
) {
if
(
node
==
null
)
return
;
findGreatestFrequency
(
node
.
left
);
if
(
current
!=
node
.
val
) {
current
=
node
.
val
;
freq
=
0
;
}
++
freq
;
maxFreq
=
Math
.
max
(
maxFreq
,
freq
);
findGreatestFrequency
(
node
.
right
);
}
private
void
findModes
(
TreeNode
node
) {
if
(
node
==
null
)
return
;
findModes
(
node
.
left
);
if
(
current
!=
node
.
val
) {
current
=
node
.
val
;
freq
=
0
;
}
++
freq
;
if
(
freq
==
maxFreq
)
modes
.
add
(
current
);
findModes
(
node
.
right
);
}
public
int
[]
findMode
(
TreeNode
root
) {
findGreatestFrequency
(
root
);
freq
=
0
;
findModes
(
root
);
int
[]
result
=
new
int
[
modes
.
size
()];
for
(
int
i
=
0
;
i
<
modes
.
size
(); ++
i
)
result
[
i
] =
modes
.
get
(
i
);
return
result
;
}
}
Back
|
FazBrowse Home
|
New Git URL