Created
February 10, 2012 17:48
-
-
Save ox/1791220 to your computer and use it in GitHub Desktop.
A function which, when given a root node, will determine if the tree is symmetric. AKA Breadth-first search
This file contains hidden or 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
#tell whether the tree is visually symmetric (it is) | |
class Node | |
attr_reader :value, :left, :right | |
def initialize(value, left, right) | |
@value, @left, @right = value, left, right | |
end | |
#added in to see output | |
def to_s; @value.to_s; end | |
def inspect; @value.to_s; end | |
end | |
i = Node.new('i', nil, nil) | |
g = Node.new('g', nil, i) | |
f = Node.new('f', nil, nil) | |
c = Node.new('c', f, g) | |
e = Node.new('e', nil, nil) | |
h = Node.new('h', nil, nil) | |
d = Node.new('d', h, nil) | |
b = Node.new('b', d, e) | |
root = Node.new('a', b, c) | |
def is_tree_symmetric?(node) | |
# the queue will be each level of the tree | |
queue = [node] | |
while !queue.empty? | |
# we compare each element with it's mirror on the other side of the queue | |
for index in 0..queue.size/2 do | |
# we only care if both are nil or both are not nil | |
if (queue[index].nil? && queue[queue.size-1-index].nil?) || | |
(!queue[index].nil? && !queue[queue.size-1-index].nil?) | |
# expand each element into its children. The element is removed | |
queue.each_index do |x| | |
sitin = [] | |
sitin = [queue[x].left] unless queue[x].nil? | |
sitin.push(queue[x].right) unless queue[x].nil? | |
queue[x] = sitin | |
end | |
queue = queue.flatten | |
# puts queue.inspect | |
else | |
# if there is anything off, the tree is not symmetric | |
return false | |
end | |
end | |
# if the queue is all nils, then we've reached the bottom of the tree | |
# compact removes nils, and an empty array means the whole queue was nils | |
if queue.compact.empty? | |
return true | |
end | |
end | |
end | |
puts is_tree_symmetric?(root) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment