Created
August 14, 2009 18:21
-
-
Save ddollar/167999 to your computer and use it in GitHub Desktop.
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
| class Node | |
| attr_reader :children | |
| attr_reader :value | |
| def initialize(value) | |
| @children = [] | |
| @value = value | |
| end | |
| def add_children(*values) | |
| values.each do |value| | |
| children << Node.new(value) | |
| end | |
| end | |
| def find_node(value) | |
| return self if value == self.value | |
| children.map { |child| child.find_node(value) }.compact.first | |
| end | |
| def print_tree | |
| nodes = [self] | |
| while nodes.length > 0 | |
| puts nodes.map { |node| node.value }.join(' ') | |
| nodes = nodes.map { |node| node.children }.flatten | |
| end | |
| end | |
| end | |
| root = Node.new('A') | |
| root.add_children('B', 'C') | |
| root.find_node('B').add_children('D', 'E') | |
| root.find_node('C').add_children('F', '0', '1') | |
| root.find_node('D').add_children('G', 'H') | |
| root.find_node('G').add_children('I', 'J') | |
| root.find_node('0').add_children('2', '3') | |
| root.print_tree |
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
| A | |
| B C | |
| D E F 0 1 | |
| G H 2 3 | |
| I J |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment