2

A bit of a newbie to computing science.

I have the basics for a binary tree in Ruby:

class Node
  attr_accessor :left, :right, :value
  def initialize(value)
    @value = value
  end
end

This works fine if I construct it manually, for example, if I want tom to be a child node of ben:

ben = Node.new('Ben')
tom = Node.new('Tom')

ben.left = tom

One of the challenges I need to figure out is how to construct a tree for inputted parent/child pairs. Here is an example input string:

peter tom
peter marie
marie john
tom oscar

My binary tree would look something like this:

    peter
      |
 tom     marie
  |        |
oscar     john

I am wondering if I can get some direction into converting multiple strings in the following format "[parent] [child]" into a binary tree.

Thanks :)

2
  • 1
    With a [parent] [child] format, how do you decide whether a child goes into left or right? Likewise, what happens if the input contains more than two child entries for a given parent? Commented Sep 5, 2016 at 14:20
  • Values can be unique ? Commented Sep 5, 2016 at 14:24

1 Answer 1

2

Use a hash to store the data:

data = Hash.new { |h, k| h[k] = Node.new k }

while !(line = gets.strip).empty?
    parent, child = line.split.map { |value| data[value] }
    if !parent.left
        parent.left = child
    elsif !parent.right
        parent.right = child
    else
        raise "#{parent.value} already has both a left and right child"
    end
end
Sign up to request clarification or add additional context in comments.

3 Comments

Nice solution, especially the way you've defined data. One small thing: you need something like while (line = gets.strip) != ''. As it is you'll never break out of the loop.
@CarySwoveland Fixed.
Awesome solution! Worked perfectly. Thanks

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.