-
Notifications
You must be signed in to change notification settings - Fork 1
/
check_balanced_tree.rb
79 lines (61 loc) · 1.29 KB
/
check_balanced_tree.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
require 'pry'
class Node
attr_accessor :value, :left, :right, :name
def initialize(options={})
@value = options[:value]
@name = options[:name]
@left = options[:left]
@right = options[:right]
end
def children?
@left && @right
end
def no_children?
@left.nil? && @right.nil?
end
def right
@right || Node.new
end
def left
@left || Node.new
end
end
def check_height(node)
return 0 if node.value == nil
left_height = check_height(node.left)
unless check_height(node.left)
return false
end
right_height = check_height(node.right)
unless check_height(node.right)
return false
end
height_diff = left_height - right_height
if height_diff.abs > 1
return false
else
return [left_height, right_height].max + 1
end
end
n10 = Node.new({:value => 10})
n5 = Node.new({:value => 5})
n15 = Node.new({:value => 15})
n3 = Node.new({:value => 3})
n12 = Node.new({:value => 12})
n5.left = n3
n5.right = n12
n10.left = n5
n10.right = n15
puts check_height(n10)
n10 = Node.new({:value => 10})
n5 = Node.new({:value => 5})
n15 = Node.new({:value => 15})
n3 = Node.new({:value => 3})
n12 = Node.new({:value => 12})
n9 = Node.new({:value => 9})
n12.left = n9
n5.left = n3
n5.right = n12
n10.left = n5
n10.right = n15
puts check_height(n10)