109.有序链表转换二叉搜索树
-
链接
leetcode
-
solution:
我是先把List转成了vector再分治
感觉这题不该在中等难度
-
code
class Solution {
public:
TreeNode* BST(int left,int right,vector<int>&list){
if(left>right) return NULL;
int mid=(left+right)>>1;
TreeNode* root=new TreeNode(list[mid]);
root->left=BST(left,mid-1,list);
root->right=BST(mid+1,right,list);
return root;
}
TreeNode* sortedListToBST(ListNode* head) {
vector<int>list;
ListNode* p=head;
while(p){
list.push_back(p->val);
p=p->next;
}
return BST(0,list.size()-1,list);
}
};