-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution109.cs
46 lines (37 loc) · 1.05 KB
/
Solution109.cs
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
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution109
{
/// <summary>
/// 109. Convert Sorted List to Binary Search Tree - Medium
/// <a href="https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree">See the problem</a>
/// </summary>
public TreeNode SortedListToBST(ListNode head)
{
if (head is null)
{
return null;
}
var list = new List<int>();
while (head is not null)
{
list.Add(head.val);
head = head.next;
}
return BuildTree(list, 0, list.Count - 1);
}
private TreeNode BuildTree(List<int> list, int start, int end)
{
if (start > end)
{
return null;
}
var mid = start + (end - start) / 2;
var root = new TreeNode(list[mid])
{
left = BuildTree(list, start, mid - 1),
right = BuildTree(list, mid + 1, end)
};
return root;
}
}