-
Notifications
You must be signed in to change notification settings - Fork 2
/
Convert Sorted List to Binary Search Tree
71 lines (64 loc) · 1.63 KB
/
Convert Sorted List to Binary Search Tree
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
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if(head == NULL)
return NULL;
ListNode* fast = head;
ListNode* slow = head;
ListNode* prev =NULL;
while(fast != NULL && fast->next != NULL)
{
fast = fast->next->next;
prev =slow;
slow=slow->next;
}
TreeNode* root = new TreeNode(slow->val);
if(prev != NULL)
prev->next = NULL;
else
head = NULL;
root->left = sortedListToBST(head);
root->right = sortedListToBST(slow->next);
return root;
}
TreeNode* sortedListToBST(ListNode* head) {
vector<int>nums;
while(head)
{
nums.push_back(head->val);
head = head->next;
}
TreeNode * root = sortedArray(nums,0,nums.size()-1);
return root;
}
TreeNode* sortedArray(vector<int>& nums,int left,int right)
{
if(left<=right)
{
int mid = (left+right)/2;
TreeNode*root = new TreeNode(nums[mid]);
root->left = sortedArray(nums,left,mid-1);
root->right = sortedArray(nums,mid+1,right);
}
else
return NULL;
}
};