Convert Sorted List to Binary Search Tree
正规做法
/**
* 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;
ListNode *slow = head;
ListNode *fast = head;
ListNode *prevSlow = NULL;
while(fast->next && fast->next->next){
prevSlow = slow;
slow = slow->next;
fast = fast->next->next;
}
TreeNode *root = new TreeNode(slow->val);
if(prevSlow){
prevSlow->next = NULL;
root->left = sortedListToBST(head);
}
root->right = sortedListToBST(slow->next);
return root;
}
};