forked from codeunion/data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree.rb
More file actions
49 lines (39 loc) · 787 Bytes
/
Copy pathtree.rb
File metadata and controls
49 lines (39 loc) · 787 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
require_relative "linked_list"
def Tree(value)
case value
when Tree
value
else
Tree.new(value)
end
end
# Implement a generic tree class. Each node
# is also a Tree and can have any number of children.
class Tree
attr_reader :value, :children
def initialize(value)
@value = value
@children = LinkedList.new
end
# Add a new child to this node
# O(1) time
def add_child(value)
@children.unshift(Tree(value))
end
def each(&block)
node = self.children.head.value
until node.nil?
block.call(node.value)
node = node.children.head.value
end
self
end
# def each(&block)
# node = self.head
# until node.empty?
# block.call(node.value)
# node = node.next
# end
# self
# end
end