-
Notifications
You must be signed in to change notification settings - Fork 0
/
poly_tree_node.rb
103 lines (79 loc) · 1.82 KB
/
poly_tree_node.rb
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
require_relative './searchable'
# represents a node in a PolyTree
class PolyTreeNode
include Searchable
attr_accessor :val
attr_reader :parent
def initialize(val = nil)
@val, @parent, @children = val, nil, []
end
def to_s
"#{@val}"
end
def children
@children.dup
end
def parent=(parent)
return if self.parent == parent
self.parent&._children&.delete(self)
@parent = parent
self.parent._children << self unless self.parent.nil?
end
def add_child(child)
child.parent = self
end
def remove_child(child)
raise "Tried to remove a node that isn't a child" if child && !children.include?(child)
child.parent = nil
end
def count(node = self)
return 0 if node.nil?
return 1 if node._children.empty?
1 + node._children.map(&:count).inject(:+)
end
protected
# Protected method to give a node direct access to another node's children.
def _children
@children
end
end
if $PROGRAM_NAME == __FILE__
node1 = PolyTreeNode.new(1)
node2 = PolyTreeNode.new(2)
node3 = PolyTreeNode.new(3)
node4 = PolyTreeNode.new(4)
node5 = PolyTreeNode.new(5)
node1.add_child(node2)
node3.parent = node1
node1.add_child(node4)
node1.add_child(node5)
# Creates the tree
#
# 1
# /| |\
# 2 3 4 5
#
puts node1.children.join(', ') # 2, 3, 4, 5
puts node1.count # 5
puts node1.bfs(4).val # 4
puts node1.bfs(4) == node4 # true
puts node1.dfs(4).val # 4
puts node1.dfs(4) == node4 # true
node6 = PolyTreeNode.new(6)
node7 = PolyTreeNode.new(7)
node8 = PolyTreeNode.new(8)
# Creates the tree
#
# 1
# /| |\
# 2 3 4 5
# / /\
# 8 6 7
#
node4.add_child(node6)
node4.add_child(node7)
node3.add_child(node8)
puts node1.count # 8
puts node3.count # 2
puts node4.count # 3
end