0

I tried to write a quick implementation for a binary search tree in Ruby, which is a data structure I commonly write when learning a new programming language.

I get stack too deep errors when I run it on my computer. I wonder if it is an issue with my code or perhaps how I'm running it?

class Node
  attr_accessor :data, :left, :right
  def initialize(d)
    @data = d
    @left = Node.new(nil)
    @right = Node.new(nil)
  end
end

class BST
  attr_accessor :root
  def initialize
    @root = nil
  end

  def add_recursive(r, d)
    if r == nil
      r = Node.new(d)
    else
      add_recursive(r.right, d) if d > r.data
      add_recursive(r.left, d) if d < r.data  
    end
  end

  def add(darg)
    add_recursive(@root, darg)
  end

  def pr(r)
    if (r.left != nil)
      pr(r.left)
    end
    print "#{r.data}"
    if (r.right != nil)
      pr(r.right)
    end
  end
end

bb = BST.new
bb.add(100)
bb.add(0)
bb.add(-100)
bb.pr(bb.root)``

I was wondering what am I doing wrong in this implementation because I did indeed run a few simple tests and my use in accessing the data variable was giving me problems. Thanks for any help

1
  • I'd probably use @left = nil and @right = nil for a new node rather than have left and right point to valid nodes that just have nil data. Commented Oct 19, 2013 at 2:35

1 Answer 1

1

You've got more than one problem here, but your infinite recursion is occurring with your first Node.new(nil) call in Node#initialize. Another problem is that you never update @root in BST after you initialize it to nil. In add_recursive your assignment to r has no effect on @root.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.