Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
由于链表不能随机访问,只能修改链表结构,要不就只能遍历求长度,再求出中间位置。
这里不能修改结构,总是要不断的遍历,求中间位置,十分罗嗦。
简单如前一题,遍历一遍,把值 push_back 到 vector<int> num 里,同前一题。
/**
* 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 *help(vector<int> &num,int a,int b){
int len = b - a + 1;
if(len <= 0 )
return NULL;
int mid = a+len/2;
TreeNode *p = new TreeNode(num[mid]);
if(len ==1)
return p;
int left_len = mid - a;
int right_len = b - mid;
if(left_len > 0)
p->left = help(num,a,a+left_len-1);
if(right_len > 0)
p->right = help(num,a+left_len+1, b);
return p;
}
TreeNode *sortedListToBST(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> num;
num.clear();
while(head)
{
num.push_back(head->val);
head = head->next;
}
int len = num.size();
if(len==0)
return NULL;
return help(num,0,len-1);
}
};