题意
思路
递归
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if (head == nullptr)
return nullptr;
if (head->next == nullptr)
return new TreeNode(head->val);
ListNode *p = head;
ListNode *q = head;
ListNode *pre = nullptr;
while (q && q->next)
{
pre = p;
p = p->next;
q = q->next->next;
}
pre->next = nullptr;
TreeNode *root = new TreeNode(p->val);
root->left = sortedListToBST(head);
root->right = sortedListToBST(p->next);
return root;
}
};
有序链表转换二叉搜索树

被折叠的 条评论
为什么被折叠?



