Created
February 17, 2012 18:02
-
-
Save rubydubee/1854652 to your computer and use it in GitHub Desktop.
Tree with compare function, the insertion is quite complex but i just wanted it to work.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require './Tree' | |
include Tree | |
root = Node.new(1) | |
root.insert(Node.new(2), -1).insert(Node.new(3), -1).insert(Node.new(3), -1) | |
root.insert(Node.new(2), 1).insert(Node.new(3), 1).insert(Node.new(3), 1) | |
root.each do |node| | |
puts "#{node.word} * " | |
end | |
if root.compare_node | |
puts "Mirror image" | |
else | |
puts "Not a Mirror image" | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Tree | |
class Node | |
attr_reader :word, :left, :right | |
include Enumerable | |
def initialize(value) | |
@word = value | |
@left = @right = nil | |
end | |
def insert(node, dir) | |
if dir < 0 | |
@left = node | |
return @left | |
else | |
@right = node | |
return @right | |
end | |
end | |
def each | |
@left.each {|node| yield node } unless @left.nil? | |
yield self | |
@right.each {|node| yield node } unless @right.nil? | |
end | |
def compare_node() | |
return compare(@left, @right) | |
end | |
# compare two nodes n1 and n2: recursive function which checks if the value is same | |
# if it is same it continues to compare (1.left and 2.right) and (1.right and 2.left) | |
def compare(n1, n2) | |
if n1.nil? && n2.nil? | |
return true | |
elsif !n1.nil? && !n2.nil? | |
if(n1.word == n2.word) | |
return compare(n1.left, n2.right) && compare(n1.right, n2.left) | |
else | |
return false | |
end | |
else | |
return false | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment