-
Notifications
You must be signed in to change notification settings - Fork 0
/
Convert Sorted List to Balanced BST.cpp
71 lines (64 loc) · 1.92 KB
/
Convert Sorted List to Balanced BST.cpp
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
66
67
68
69
70
71
/*
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Link: http://www.lintcode.com/en/problem/convert-sorted-list-to-balanced-bst/
Example:
2
1->2->3 => / \
1 3
Solution: None
Source: https://github.com/kamyu104/LintCode/blob/master/C%2B%2B/convert-sorted-list-to-binary-search-tree.cpp
*/
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: a tree node
*/
TreeNode *sortedListToBST(ListNode *head) {
// write your code here
ListNode *curr = head;
int n = 0;
while (curr) {
curr = curr->next;
++n;
}
return BuildBSTFromSortedDoublyListHelper(&head, 0, n);
}
// Builds a BST from the (s + 1)-th to the e-th node in L, and returns the
// root. Node numbering is from 1 to n.
TreeNode * BuildBSTFromSortedDoublyListHelper(ListNode **L, int s, int e) {
if (s >= e) {
return nullptr;
}
int m = s + ((e - s) / 2);
TreeNode *left = BuildBSTFromSortedDoublyListHelper(L, s, m);
TreeNode *curr = new TreeNode((*L)->val); // The last function call sets L to the successor of the
// maximum node in the tree rooted at left.
*L = (*L)->next;
curr->left = left;
curr->right = BuildBSTFromSortedDoublyListHelper(L, m + 1, e);
return curr;
}
};