This repository has been archived by the owner on Jan 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exercise11.rb
79 lines (63 loc) · 1.44 KB
/
exercise11.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
# Exercise 11
class BinaryNode
attr_accessor :leftChild, :rightChild, :name
def initialize(name)
@name = name
end
end
def preorder(node)
puts node.name
unless(node.leftChild.nil?) then preorder(node.leftChild) end
unless(node.rightChild.nil?) then preorder(node.rightChild) end
end
def inorder(node)
unless(node.leftChild.nil?) then inorder(node.leftChild) end
puts node.name
unless(node.rightChild.nil?) then inorder(node.rightChild) end
end
def postorder(node)
unless(node.leftChild.nil?) then postorder(node.leftChild) end
unless(node.rightChild.nil?) then postorder(node.rightChild) end
puts node.name
end
def depthfirst(node)
queue = []
queue.push(node)
while(!queue.empty?)
nd = queue.shift
puts nd.name
unless(nd.leftChild.nil?) then queue.push(nd.leftChild) end
unless(nd.rightChild.nil?) then queue.push(nd.rightChild) end
end
end
ROOT = BinaryNode.new("E")
a = BinaryNode.new("A")
b = BinaryNode.new("B")
c = BinaryNode.new("C")
d = BinaryNode.new("D")
f = BinaryNode.new("F")
g = BinaryNode.new("G")
h = BinaryNode.new("H")
i = BinaryNode.new("I")
j = BinaryNode.new("J")
# left side
ROOT.leftChild = b
b.leftChild = a
b.rightChild = d
d.leftChild = c
# right side
ROOT.rightChild = f
f.rightChild = i
i.rightChild = j
i.leftChild = g
g.rightChild = h
=begin
puts "Preorder:"
preorder(ROOT)
puts "Inorder:"
inorder(ROOT)
puts "Postorder:"
postorder(ROOT)
puts "Depthfirst:"
depthfirst(ROOT)
=end