-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.rb
More file actions
65 lines (43 loc) · 1.1 KB
/
Solution.rb
File metadata and controls
65 lines (43 loc) · 1.1 KB
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
# Definition for a binary tree node.
class TreeNode
attr_accessor :val, :left, :right
def initialize(val)
@val = val
@left, @right = nil, nil
end
end
# @param {TreeNode} root
# @return {Boolean}
def is_balanced(root)
if root.nil?
return true
end
l_height, l_balanced = subtree_height root.left
r_height, r_balanced = subtree_height root.right
unless l_balanced and r_balanced
return false
end
unless -1 <= l_height - r_height and l_height - r_height <= 1
return false
end
true
end
def subtree_height(node)
if node.nil?
return 0, true
end
leftHeight, leftBalanced = subtree_height node.left
rightHeight, rightBalanced = subtree_height node.right
unless leftBalanced and rightBalanced
return 0, false
end
balancedValue = leftHeight - rightHeight
balanced = if balancedValue < -1 or balancedValue > 1 then false else true end
unless balanced
return 0, false
end
maxHeight = if leftHeight > rightHeight then leftHeight else rightHeight end
return maxHeight + 1, true
end
root = TreeNode.new(1)
puts is_balanced root