title: Leetcode #501 - Find mode in binary tree: Trouble with recursion and pass-by-reference
body: <p>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.</p>
  
  <p>Using instance variables, the following code works:</p>
  
  <pre><code>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 &gt; @max
      @max = @counter
      @modes = [node.val]
    elsif @counter == @max
      @modes &lt;&lt; node.val
    end
  
    @prev = node
  
    inorder(node.right)
  end
  </code></pre>
  
  <p>However, the following alternate version does not work. Instead it times out.</p>
  
  <pre><code>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 &gt; max
      max = counter
      modes = [node.val]
    elsif counter == max
      modes &lt;&lt; node.val
    end
    prev = node
  
    inorder(node.right, modes, node, counter, max)
  end
  </code></pre>
  
  <p>What am I failing to understand in the second approach?</p>