-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathfind_mode_in_BST.rb
More file actions
49 lines (47 loc) · 979 Bytes
/
find_mode_in_BST.rb
File metadata and controls
49 lines (47 loc) · 979 Bytes
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
def find_mode(root)
stack, pre, count, max_count, result = [], nil, 0, 0, []
while root || stack.any?
while root
stack << root
root = root.left
end
root = stack.pop
if pre && pre.val == root.val
count += 1
else
count = 1
end
if max_count < count
max_count = count
result = [root.val]
elsif max_count == count
result << root.val
end
pre = root
root = root.right
end
result
end
# Q-501: recursive way is bad, hard to bring reference in recursive-body
def find_mode_recur(root)
@result, @count, @max_count, @pre = [], 0, 0, nil
search(root, nil)
@result
end
def search(root, pre)
return unless root
search(root.left, pre)
if @pre && @pre.val == root.val
@count += 1
else
@count = 1
end
if @count > @max_count
@result = [root.val]
@max_count = @count
elsif @count == @max_count
@result << root.val
end
@pre = root
search(root.right, pre)
end