-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.rb
More file actions
48 lines (32 loc) · 724 Bytes
/
Solution.rb
File metadata and controls
48 lines (32 loc) · 724 Bytes
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
# 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 {Integer[]} nums
# @return {TreeNode}
def sorted_array_to_bst(nums)
if nums.nil? or nums.size < 1
return nil
end
form_node nums, 0, nums.size - 1
end
def form_node(nums, left, right)
if left > right
return nil
end
if left == right
return TreeNode.new nums[left]
end
mid = left + Integer((right - left) / 2)
root = TreeNode.new nums[mid]
root.left = form_node nums, left, mid - 1
root.right = form_node nums, mid + 1, right
root
end
root = sorted_array_to_bst [1, 3]
puts root.val
puts root.right.val