Skip to content

Commit 9db223d

Browse files
authored
Update 501-find-mode-in-binary-search-tree.js
1 parent d6dd137 commit 9db223d

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

501-find-mode-in-binary-search-tree.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,28 @@ function traverse(node, hash) {
2828
traverse(node.left, hash)
2929
traverse(node.right, hash)
3030
}
31+
32+
33+
// another
34+
const findMode = function(root) {
35+
let res = [];
36+
let cnt = 1;
37+
let mx = 0;
38+
let pre = null;
39+
let search = function(node) {
40+
if (!node) return;
41+
search(node.left);
42+
if (pre) {
43+
cnt = (node.val === pre.val) ? cnt + 1 : 1;
44+
}
45+
if (cnt >= mx) {
46+
if (cnt > mx) res.length = 0;
47+
res.push(node.val);
48+
mx = cnt;
49+
}
50+
pre = node;
51+
search(node.right);
52+
}
53+
search(root);
54+
return res;
55+
};

0 commit comments

Comments
 (0)