I believe my code works in one scenario and breaks in another for the Leetcode problem #501 due to gaps in my understanding of recursion and pass-by-reference concepts in Ruby.
Using instance variables, the following code works:
def find_mode(root)
return [] if root.nil?
@modes = []
@counter = 1
@max = 0
@prev = nil
inorder(root)
@modes
end
def inorder(node)
return if node.nil?
inorder(node.left)
if !@prev.nil?
if @prev.val == node.val
@counter += 1
else
@counter = 1
end
end
if @counter > @max
@max = @counter
@modes = [node.val]
elsif @counter == @max
@modes << node.val
end
@prev = node
inorder(node.right)
end
However, the following alternate version does not work. Instead it times out.
def find_mode(root)
return [] if root.nil?
modes = []
counter = 1
max = 0
prev = nil
inorder(root, modes, prev, counter, max)
modes
end
def inorder(node, modes, prev, counter, max)
return if node.nil?
inorder(node.left, modes, node, counter, max)
if !prev.nil?
if prev.val == node.val
counter += 1
else
counter = 1
end
end
if counter > max
max = counter
modes = [node.val]
elsif counter == max
modes << node.val
end
prev = node
inorder(node.right, modes, node, counter, max)
end
What am I failing to understand in the second approach?