/**
* 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 *sortedListToBST(ListNode *head) {
if(head==NULL) return NULL;
//一个结点
if(head->next==NULL)
{
TreeNode *ret=new TreeNode(head->val);
return ret;
}
//两个以上结点
ListNode *pre=NULL,*slow=head,*fast=head;
while(fast->next && fast->next->next)
{
pre=slow;
slow=slow->next;
fast=fast->next->next;
}
//slow指向List的中间结点
TreeNode *root=new TreeNode(slow->val);
if(pre!=NULL)
{
pre->next=NULL;
root->left=sortedListToBST(head);
}
else
{
root->left=sortedListToBST(NULL);
}
root->right=sortedListToBST(slow->next);
return root;
}
};
Convert Sorted List to Binary Search Tree
最新推荐文章于 2021-02-02 14:31:21 发布