Skip to content

Commit 9dab523

Browse files
authored
Merge pull request #25 from remy727/convert-sorted-list-to-binary-search-tree
109. Convert Sorted List to Binary Search Tree
2 parents 25a4aca + 06925f0 commit 9dab523

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
| 91 | Decode Ways | [Ruby](./algorithms/ruby/0091-decode-ways.rb) | Medium |
3030
| 103 | Binary Tree Zigzag Level Order Traversal | [Ruby](./algorithms/ruby/0103-binary-tree-zigzag-level-order-traversal.rb) | Medium |
3131
| 104 | Maximum Depth of Binary Tree | [Ruby](./algorithms/ruby/0104-maximum-depth-of-binary-tree.rb) [Python3](./algorithms/python3/0104-maximum-depth-of-binary-tree.py) | Easy |
32+
| 109 | Convert Sorted List to Binary Search Tree | [Ruby](./algorithms/ruby/0109-convert-sorted-list-to-binary-search-tree.rb) | Medium |
3233
| 113 | Path Sum II | [Ruby](./algorithms/ruby/0113-path-sum-ii.rb) | Medium |
3334
| 121 | Best Time to Buy and Sell Stock | [Ruby](./algorithms/ruby/0121-best-time-to-buy-and-sell-stock.rb) | Easy |
3435
| 142 | Linked List Cycle II | [Ruby](./algorithms/ruby/0142-linked-list-cycle-ii.rb) | Medium |
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# frozen_string_literal: true
2+
3+
# Problem: 109. Convert Sorted List to Binary Search Tree
4+
# URL: https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree
5+
6+
=begin
7+
8+
Given the head of a singly linked list where elements are sorted in ascending order, convert it to a
9+
height-balanced binary search tree.
10+
11+
# Constraints:
12+
13+
* The number of nodes in head is in the range [0, 2 * 104].
14+
* -105 <= Node.val <= 105
15+
16+
=end
17+
18+
# Definition for singly-linked list.
19+
# class ListNode
20+
# attr_accessor :val, :next
21+
# def initialize(val = 0, _next = nil)
22+
# @val = val
23+
# @next = _next
24+
# end
25+
# end
26+
# Definition for a binary tree node.
27+
# class TreeNode
28+
# attr_accessor :val, :left, :right
29+
# def initialize(val = 0, left = nil, right = nil)
30+
# @val = val
31+
# @left = left
32+
# @right = right
33+
# end
34+
# end
35+
# @param {ListNode} head
36+
# @return {TreeNode}
37+
def sorted_list_to_bst(head)
38+
a = []
39+
while head
40+
a << head.val
41+
head = head.next
42+
end
43+
f = -> i, j do
44+
return nil if i >= j
45+
m = (i + j) / 2
46+
TreeNode.new a[m], f.(i, m), f.(m + 1, j)
47+
end
48+
f.(0, a.size)
49+
end

0 commit comments

Comments
 (0)