/**
* 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) {}
* };
*/
TreeNode* f(ListNode*head,int lo,int hi) {
if(lo<=hi) {
int mid = (lo+hi)/2;
if (mid*2!=lo+hi) mid=mid+1;
ListNode* p=head; int k=1;
while(k!=mid) {p=p->next;k++;}
TreeNode* root = new TreeNode(p->val);
root->left=f(head,lo,mid-1);
root->right=f(head,mid+1,hi);
return root;
}
return NULL;
}
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
ListNode* tmp = head;
int len=0; while(tmp){tmp=tmp->next;len++;}
TreeNode* root = f(head,1,len);
return root;
}
};
convert-sorted-list-to-binary-search-tree
最新推荐文章于 2018-08-06 10:30:28 发布