/**
* 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)
return NULL;
ListNode *pre=NULL;
ListNode *slow=head;
ListNode *fast=head;
while(fast->next!=NULL)
{
fast=fast->next;
if(fast->next==NULL)
break;
fast=fast->next;
pre=slow;
slow=slow->next;
}
if(pre)pre->next=NULL;
else head=NULL;
TreeNode *root=new TreeNode(slow->val);
root->left=sortedListToBST(head);
root->right=sortedListToBST(slow->next);
return root;
}
109. Convert Sorted List to Binary Search Tree

最新推荐文章于 2020-04-13 06:45:19 发布
