有序链表转换二叉搜索树
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8ba5bef5028c924214d41f0610d9b16a.png)
/**
* 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==NULL)
return NULL;
auto result=ToBST(head,NULL);
return result;
}
TreeNode* ToBST(ListNode* head, ListNode* tail)
{
//使用什么方法呢
if (head == tail)
return NULL;
ListNode* fast = head;
ListNode* slow = head;
while (fast != tail&&fast->next != tail)
{
fast = fast->next->next;
slow = slow->next;
}
TreeNode* root = new TreeNode(slow->val);
root->left = ToBST(head, slow);
root->right = ToBST(slow->next,tail);
return root;
}
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f4c20f7a9b6505664efde4ea75c4bf60.png)