Skip to content

Instantly share code, notes, and snippets.

@RasPhilCo
Last active May 20, 2016 19:44
Show Gist options
  • Save RasPhilCo/752b97495aa03b970d00254ad47b1ae5 to your computer and use it in GitHub Desktop.
Save RasPhilCo/752b97495aa03b970d00254ad47b1ae5 to your computer and use it in GitHub Desktop.
Ruby tree with BF and DF traversal
# extended from https://stackoverflow.com/questions/10661610/implement-a-tree-iterator
class Node
attr_accessor :data, :children
def initialize(data, *children)
@data = data
@children = children
end
def traverse_depth(&block)
yield self
children.each {|child| child.traverse_depth(&block)}
end
def traverse_breadth(&block)
queue = [self]
while !queue.empty?
node = queue.shift
yield node
queue += node.children
end
end
end
z = Node.new("d", Node.new("0"))
b = Node.new("b", z)
c = Node.new("c", Node.new("e"))
root = Node.new("A", b, c)
str = ''
root.traverse_depth {|node| str += node.data}
print str
puts
str = ''
root.traverse_breadth {|node| str += node.data}
print str
@RasPhilCo
Copy link
Author

RasPhilCo commented May 20, 2016

def find(elm, tree)
 tree.traverse_depth  { |node| return node.data if node.data == elm }  # or: tree.traverse_breadth...
end

puts find "0", root

@RasPhilCo
Copy link
Author

Alternatively, node, *queue = queue in-place of node = queue.shift

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment