Note:
跟给数组去构建一样,就是每次去找中点,然后两边去递归分治
链表找中点,就用快慢指针, 一个每次走一步,一个走两步,走两步的到头了, 走一步的就是到了中点了
代码如下:
/**
* 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) {
return dfs(head, NULL);
}
ListNode* getMid(ListNode* left, ListNode* right){
ListNode* fast = left, *slow = left;
while(fast != right && fast -> next != right){
fast = fast -> next;
fast = fast -> next;
slow = slow -> next;
}
return slow;
}
TreeNode* dfs(ListNode* left, ListNode* right){
if(left == right)
return NULL;
ListNode * mid = getMid(left, right);
auto root = new TreeNode(mid -> val);
root -> left = dfs(left, mid);
root -> right = dfs(mid -> next, right);
return root;
}
};