I have a binary tree implementation as below. I'd like to add a method that recursively sums up all node values of the binary tree:
class BST
class Node
attr_reader :value, :left, :right
def initialize(value)
#value = value
#left = nil
#right = nil
end
def insert(value)
if value <= #value
#left.nil? ? #left = Node.new(value) : #left.insert(value)
elsif value > #value
#right.nil? ? #right = Node.new(value) : #right.insert(value)
end
end
end
def initialize
#root = nil
end
def insert(value)
#root.nil? ? #root = Node.new(value) : #root.insert(value)
end
end
I found the answer for other languages, however unfortunately not for Ruby.
I think your code in the comments was:
def sum(node=#root)
return if node.nil?
total += node.value
sum(node.left)
sum(node.right)
end
The idea is almost okay. There is no summing in nil nodes; and you total up the current node's value, the left node and the right node. Here's the mistakes:
total += node.value is the first time we see total. This initialises it to nil. When you try to add node.value to it, you get the error you described. To avoid it, either total must already exist, or you can just assign node.value to it.
If a function ends without executing a return statement, it returns the last evaluated expression; in this case, sum(node.right). Wouldn't it be better if sum returned total?
Conversely, sum(node.left) will presumably do some summing... but its return value is discarded. It might make sense to add it to the total. Speaking of totals, maybe we should do the same for sum(node.right).
Finally, return if node.nil? says you refuse to sum the nodes that are not actually nodes. That's great... except that return returns nil, and if you try to total a nil with something, it doesn't go well. There are two solutions here: refuse to total a node before you enter it, or say that a nil node has value 0, which does not affect a sum.
Taking it all together, here's my two versions:
# refuse to enter a nil node:
def sum(node=#root)
total = node.value
total += sum(node.left) unless node.left.nil?
total += sum(node.right) unless node.right.nil?
total
end
# treat nil nodes as if they were zeroes:
def sum(node=#root)
return 0 if node.nil?
node.value + sum(node.left) + sum(node.right)
end
Related
I was trying to implement a ruby binary search tree, creating, adding and printing node is fine, the problem rose when i was implementing #delete
(i will post the code below) the structure for this tree is nested binary nodes (why? I am no nothing about ruby pointers)
class BinaryNode
attr_accessor :value
attr_accessor :left_node
attr_accessor :right_node
def initialize (value = nil, left_node = nil, right_node = nil)
#value = value
#left_node = left_node
#right_node = right_node
end
end
the left and right nodes will be another binary node, and it goes on
so when i want to insert a node (which is fine), i use a temp binary node to traverse the tree and when i reach my goal (if no duplicates encountered) I simply make the temp's child (left or right according to comparison), but why this works, i mean i copied the binary node, AND modified the COPIED one, but works,
here is the #insert if you need more insight
def insert (value, node = #root)
if value == node.value
return nil
elsif value > node.value
if node.right_node == nil
node.right_node = BinaryNode.new(value)
else
insert value, node.right_node
end
else
if node.left_node == nil
node.left_node = BinaryTree.new(value)
else
insert value, node.left_node
end
end
end
now when i apply the same logic for deleting node (currently stuck with leaves, have not yet explored and tested other cases) it fail, here is the code if my statement is not sufficient
def delete (value)
temp = #root
sup_node = temp
while temp.value != value
puts "currently at #{temp.value}"
if temp.value > value
temp = temp.left_node
puts "going left"
elsif temp.value < value
temp = temp.right_node
puts "going right"
end
target_node = temp
puts "target_node: #{target_node.value}"
end
if target_node.right_node == nil
puts "right node is nil"
if target_node.left_node == nil
puts "left node is nil"
puts "deleting node"
target_node = nil
else
temp_node = target_node.left_node
target_node.left_node = nil
target_node = temp_node
end
else
target_node_right = target_node.right_node
last_left_node = target_node_right
while last_left_node.left_node != nil
last_left_node = last_left_node.left_node
end
if last_left_node.right_node == nil
target_node.value = last_left_node.value
last_left_node = nil
else
last_left_parent_node = target_node_right
while last_left_parent_node.left_node != last_left_node
last_left_parent_node == last_left_parent_node.left_node
end
#some chaos going on here
last_left_parent_node.right_node = last_left_node.right
last_left_parent_node.left_node = nil
target_node.value = last_left_node.value
last_left_node = nil
end
end
end
My main question why an approach works fine in one situation but break in another, and how ruby can track copied data, and modify original, I am not interested in the binary tree algorithms it self (any problem probably will be easily searchable)
Thanks in advance
by the way sorry for being long, if you want the whole code (although I think what i copied is sufficient) you can find it on github
I'm implementing a binary search tree in ruby, and I'm attempting to define a function to remove an value from the tree. The Tree has a #root value that points to a Node object. which is defined as such:
class Node
attr_reader :value
attr_accessor :left, :right
def initialize value=nil
#value = value
#left = nil
#right = nil
end
# Add new value as child node to self, left or ride
# allows for duplicates, to L side of tree
def insert new_value
if new_value <= #value
#left.nil? ? #left = Node.new(new_value) : #left.insert(new_value)
elsif new_value > #value
#right.nil? ? #right = Node.new(new_value) : #right.insert(new_value)
end
end
end
Thus, the nodes all hold references to their L & R children. Everything works on the tree, inserting, traversing, performing a breadth-first-search (level-order-traverse) to return a Node value, if found.
The problem I'm having is when trying to remove a Node object. I can't figure out how to set the actual OBJECT to nil, or to its child, for example, rather than reassigning a POINTER/variable to nil and the object still existing.
Tree has two functions that are supposed to do this (you can assume that breadth_first_search correctly returns the appropriate found node, as does smallest_r_child_of)
def remove value
node = breadth_first_search(value)
return false if node.nil?
remove_node(node)
end
def remove_node node
if node.left.nil? && node.right.nil?
node = nil
elsif !node.left.nil? && node.right.nil?
node = node.left
elsif node.left.nil? && !node.right.nil?
node = node.right
else
node = smallest_r_child_of(node)
end
return true
end
I thought that by passing in the actual node object to remove_node, that I could call node = ____ and the like to reassign the actual object to something else, but all it does, as far as I can tell, is reset the node argument variable/pointer, while not actually reassigning my data at all.
Does anyone have any tips/suggestions on how to accomplish what I'm trying to do?
You cannot "set an object to nil". An object can never change its class, it either is an instance of Node or it is an instance of NilClass, it cannot at one point in time be an instance of Node and at another point in time be an instance of NilClass.
Likewise, an object cannot change its identity, object #4711 will always be object #4711, however, nil is a singleton, so there is only one nil and it has the same identity during the entire lifetime of the system.
What you can do is to bind the variable which references the object to nil. You are doing the opposite operation inside your insert method.
I am in the process of learning Ruby and as practice I am making a linked list class. I am in the process of writing the delete method for a doubly linked list. My question is, if I represent the list by its head node, how do I delete the head? It seems like Ruby wont allow you to assign to the self variable, so I can't change the reference of the caller to be the next node. One solution is that I can copy the key from the next node and swap references, but in general, is there a way in Ruby to change the reference of the caller?
class LinkedListNode
attr_accessor :next, :previous, :key
def initialize(key=nil, next_node=nil, previous=nil)
#next = next_node
#previous = previous
#key = key
end
def append(key=nil)
newnode = LinkedListNode.new(key)
seeker = self
while seeker.next != nil
seeker = seeker.next
end
newnode.previous = seeker
seeker.next = newnode
end
def delete(key=nil)
seeker = self
while seeker.key != key
return if seeker.next == nil
seeker = seeker.next
end
if seeker.previous != nil
if seeker.next != nil
seeker.previous.next = seeker.next
seeker.next.previous = seeker.previous
else
seeker.previous.next = nil
end
else
return self = self.next
end
return seeker = nil
end
def print
seeker = self
string = ""
while 1
if seeker.next == nil
string += seeker.key.to_s
break
else
string += seeker.key.to_s + " -> "
end
seeker = seeker.next
end
puts string
end
end
if __FILE__ == $0
ll = LinkedListNode.new(1)
ll.append(2)
ll.append(3)
ll.append(4)
ll.append(5)
ll.print
ll.delete(5)
ll.print
ll.delete(1)
ll.print
end
You can't change the which object is being pointed to by the caller (i.e. modify self), but you can manipulate the object in any way you want, as you've already thought through. The short answer is that it can't be done. You can come up with other ways to model it, but I think you're already on the right track.
You need to conceptualize a linked list differently. A LinkedListNode is a component of a LinkedList, not a LinkedList itself. Operations such as append, delete, and print should go in your LinkedList class, not your LinkedListNode class. Try starting with something like
class LinkedList
# This one-liner defines a LinkedList::Node with associated constructor
# and accessors for the three tags provided. Any tags omitted during
# construction will be initialized to nil.
Node = Struct.new(:key, :previous, :next)
attr_reader :head, :tail
def initialize
# start with no Nodes in the list
#head = #tail = nil
end
def append(key)
# Make the LinkedList tail a new node that stores the key,
# points to the prior tail as its previous reference, and
# has no next.
#tail = Node.new(key, #tail)
if #tail.previous # the prior tail was not nil
#tail.previous.next = #tail # make the prior tail point to the new one
else # if there wasn't any tail before the list was empty
#head = #tail # so the new tail Node is also the head
end
end
# ...
end
First of all, for those of you, who don't know (or forgot) about Lychrel numbers, here is an entry from Wikipedia: http://en.wikipedia.org/wiki/Lychrel_number.
I want to implement the Lychrel number detector in the range from 0 to 10_000. Here is my solution:
class Integer
# Return a reversed integer number, e.g.:
#
# 1632.reverse #=> 2361
#
def reverse
self.to_s.reverse.to_i
end
# Check, whether given number
# is the Lychrel number or not.
#
def lychrel?(depth=30)
if depth == 0
return true
elsif self == self.reverse and depth != 30 # [1]
return false
end
# In case both statements are false, try
# recursive "reverse and add" again.
(self + self.reverse).lychrel?(depth-1)
end
end
puts (0..10000).find_all(&:lychrel?)
The issue with this code is the depth value [1]. So, basically, depth is a value, that defines how many times we need to proceed through the iteration process, to be sure, that current number is really a Lychrel number. The default value is 30 iterations, but I want to add more latitude, so programmer can specify his own depth through method's parameter. The 30 iterations is perfect for such small range as I need, but if I want to cover all natural numbers, I have to be more agile.
Because of the recursion, that takes a place in Integer#lychrel?, I can't be agile. If I had provided an argument to the lychrel?, there wouldn't have been any changes because of the [1] statement.
So, my question sounds like this: "How do I refactor my method, so it will accept parameters correctly?".
What you currently have is known as tail recursion. This can usually be re-written as a loop to get rid of the recursive call and eliminate the risk of running out of stack space. Try something more like this:
def lychrel?(depth=30)
val = self
first_iteration = true
while depth > 0 do
# Return false if the number has become a palindrome,
# but allow a palindrome as input
if first_iteration
first_iteration = false
else
if val == val.reverse
return false
end
# Perform next iteration
val = (val + val.reverse)
depth = depth - 1
end
return true
end
I don't have Ruby installed on this machine so I can't verify whether that 's 100% correct, but you get the idea. Also, I'm assuming that the purpose of the and depth != 30 bit is to allow a palindrome to be provided as input without immediately returning false.
By looping, you can use a state variable like first_iteration to keep track of whether or not you need to do the val == val.reverse check. With the recursive solution, scoping limitations prevent you from tracking this easily (you'd have to add another function parameter and pass the state variable to each recursive call in turn).
A more clean and ruby-like solution:
class Integer
def reverse
self.to_s.reverse.to_i
end
def lychrel?(depth=50)
n = self
depth.times do |i|
r = n.reverse
return false if i > 0 and n == r
n += r
end
true
end
end
puts (0...10000).find_all(&:lychrel?) #=> 249 numbers
bta's solution with some corrections:
class Integer
def reverse
self.to_s.reverse.to_i
end
def lychrel?(depth=30)
this = self
first_iteration = true
begin
if first_iteration
first_iteration = false
elsif this == this.reverse
return false
end
this += this.reverse
depth -= 1
end while depth > 0
return true
end
end
puts (1..10000).find_all { |num| num.lychrel?(255) }
Not so fast, but it works:
code/practice/ruby% time ruby lychrel.rb > /dev/null
ruby lychrel.rb > /dev/null 1.14s user 0.00s system 99% cpu 1.150 total
My friends and I are working on some basic Ruby exercises to get a feel for the language, and we've run into an interesting behavior that we're yet unable to understand. Basically, we're creating a tree data type where there's just one class, node, which contains exactly one value and an array of zero or more nodes. We're using rspec's autospec test runner. At one point we started writing tests to disallow infinite recursion (a circular tree structure).
Here's our test:
it "breaks on a circular reference, which we will fix later" do
tree1 = Node.new 1
tree2 = Node.new 1
tree2.add_child tree1
tree1.add_child tree2
(tree1 == tree2).should be_false
end
Here's the Node class:
class Node
attr_accessor :value
attr_reader :nodes
def initialize initial_value = nil
#value = initial_value
#nodes = []
end
def add_child child
#nodes.push child
#nodes.sort! { |node1, node2| node1.value <=> node2.value }
end
def == node
return (#value == node.value) && (#nodes == node.nodes)
end
end
We expect the last line of the test to result in an infinite recursion until the stack overflows, because it should continually compare the child nodes with each other and never find a leaf node. (We're under the impression that the == operator on an array will iterate over the array and call == on each child, based on the array page of RubyDoc.) But if we throw a puts into the == method to see how often it's called, we discover that it's called exactly three times and then the test passes.
What are we missing?
Edit: Note that if we replace be_false in the test with be_true then the test fails. So it definitely thinks the arrays are not equal, it's just not recursing over them (aside from the three distinct calls to ==).
If you click on the method name of the RubyDoc you linked to, you will see the source (in C) of the Array#== method:
{
// [...]
if (RARRAY(ary1)->len != RARRAY(ary2)->len) return Qfalse;
if (rb_inspecting_p(ary1)) return Qfalse;
return rb_protect_inspect(recursive_equal, ary1, ary2);
}
This implementation (specifically the "recursive_equal") suggests that Array#== already implements the infinite recursion protection you're after.