-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertSortedListtoBinarySearchTree.cpp
More file actions
58 lines (48 loc) · 1.39 KB
/
ConvertSortedListtoBinarySearchTree.cpp
File metadata and controls
58 lines (48 loc) · 1.39 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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int size = countList(head);
return sortedListToBSTRecur(&head, size);
}
private:
// construct the tree bottum-up
TreeNode *sortedListToBSTRecur(ListNode **headPtr, int n) {
//base case:
if (n <= 0) return NULL;
TreeNode *leftSubTree = sortedListToBSTRecur(headPtr, n/2);
//Note, *headPtr is already changed by the previous recursive call.
TreeNode *root = new TreeNode( (*headPtr)->val );
root->left = leftSubTree;
//move to next node
*headPtr = (*headPtr)->next;
root->right = sortedListToBSTRecur(headPtr, n - n/2 - 1);
return root;
}
int countList(ListNode *head) {
int count = 0;
while (head != NULL) {
count++;
head = head->next;
}
return count;
}
};