Last active
May 20, 2016 19:44
-
-
Save RasPhilCo/752b97495aa03b970d00254ad47b1ae5 to your computer and use it in GitHub Desktop.
Ruby tree with BF and DF traversal
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
# 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 |
Author
RasPhilCo
commented
May 20, 2016
•
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