-
Notifications
You must be signed in to change notification settings - Fork 0
/
isItBalanced.rb
46 lines (36 loc) · 891 Bytes
/
isItBalanced.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
class Node
attr_reader :data
attr_accessor :left, :right
def initialize data
@data = data
end
end
# helper function
def array_to_tree(array, index = 0)
return nil if index >= array.length || array[index] == 0
node = Node.new(array[index])
node.left = array_to_tree(array, 2*index+1)
node.right = array_to_tree(array, 2*index+2)
node
end
# helper function
def height(node, h = 1)
return h if node.nil?
h += height(node.left, h)
h
end
def balanced_tree?(array)
root = array_to_tree(array)
balanced?(root)
end
def balanced? (node)
return true if node.nil?
left_height = height(node.left)
right_height = height(node.right)
return false if (left_height - right_height).abs > 1
balanced?(node.left) && balanced?(node.right)
end
puts balanced_tree?([1, 2, 0, 3, 4, 0, 0])
# => false
puts balanced_tree?([1, 2, 3, 4, 5, 6, 7])
# => true