Convert Sorted List to Binary Search Tree
解法:
把链表转换为vector之后,解法和上题一样。
class Solution {
public:
TreeNode *sortedListToBSTbyIndex(vector<int> &num,int begin,int end){
if (begin>end) {
return nullptr;
}
int mid=begin+(end-begin)/2;
TreeNode *pleft=sortedListToBSTbyIndex(num, begin, mid-1);
TreeNode *pright=sortedListToBSTbyIndex(num, mid+1, end);
TreeNode *node=new TreeNode(num[mid]);
node->left=pleft;
node->right=pright;
return node;
}
TreeNode *sortedListToBST(ListNode *head) {
if (head==nullptr) {
return nullptr;
}
vector<int> vt;
while (head!=nullptr) {
vt.push_back(head->val);
head=head->next;
}
return sortedListToBSTbyIndex(vt,0,vt.size()-1);
}
};