Last active
December 23, 2015 14:19
-
-
Save jhamon/6647976 to your computer and use it in GitHub Desktop.
A simple implementation of nodes in a tree. Each tree can have arbitrarily many child nodes.
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
class TreeNode | |
attr_accessor :parent, :children | |
attr_reader :value | |
def initialize(value) | |
@value = value | |
@parent = nil | |
@children = [] | |
end | |
def children=(array) | |
# Accepts an array of TreeNode instances, or an array of values | |
# you wish to create nodes for. | |
@children = array | |
@children.map!{|val| TreeNode.new(val)} if !array[0].is_a? TreeNode | |
@children.each { |node| node.parent = self } | |
end | |
def dfs(target_value) | |
# Depth-first search. Returns TreeNode instance | |
# with target value, or nil if not in tree. | |
return self if @value == target_value | |
found_node = nil | |
@children.each do |child| | |
found_node = child.dfs(target_value) | |
return found_node unless found_node.nil? | |
end | |
found_node | |
end | |
def path | |
# returns an array of TreeNode instances | |
# from self to the tree root. | |
path = [self] | |
current_node = self | |
until current_node.parent.nil? # root's parent is nil | |
path << current_node.parent | |
current_node = current_node.parent | |
end | |
path.reverse | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment