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
/
exercise15.rb
103 lines (86 loc) · 2.08 KB
/
exercise15.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 'exercise14.rb'
# Exercise 15
class BinaryNode
def positionSubtree
if(@leftChild.nil?&&@rightChild.nil?)
return
elsif([email protected]?&&@rightChild.nil?)
@leftChild.x = @x - 100
@leftChild.y = @y + 100
@leftChild.positionSubtree
elsif(@leftChild.nil?&&[email protected]?)
@rightChild.x = @x + 100
@rightChild.y = @y + 100
@rightChild.positionSubtree
else
# position left subtree
@leftChild.x = @x-100
@leftChild.y = @y+100
@leftChild.positionSubtree
# move whole subtree to the left part if necessary
leftMaxX = @leftChild.maxRight
if(leftMaxX>=@x)
@leftChild.moveTree(-(leftMaxX-@x+SPACE))
end
# position right subtree
@rightChild.x = @x + 100
@rightChild.y = @y + 100
@rightChild.positionSubtree
# move whole subtree to the right part if necessary
rightMinX = @rightChild.maxLeft
if(rightMinX<=@x)
@rightChild.moveTree(@x-rightMinX+SPACE)
end
end
end
# max x value
def maxRight
if(@rightChild.nil?&&@leftChild.nil?)
return @x
elsif([email protected]?)
return @rightChild.maxRight
else
return @x+100 # space for absent child
end
end
# min x value
def maxLeft
if(@leftChild.nil?&&@rightChild.nil?)
return @x
elsif([email protected]?)
return @leftChild.maxLeft
else
return @x-100 # space for absent child
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
# c.leftChild = BinaryNode.new("Z")
# c.rightChild = BinaryNode.new("R")
# d.rightChild = BinaryNode.new("U")
# root.x = 900
# root.y = 100
# root.positionSubtree
# root.draw
# root.drawLines
# show