思路:和有序数组转换二叉树类似。只需要将有序链表转换为有序数组,然后用二分法就可以。
/**
* 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) {
vector<int> nums;
ListNode* cur=head;
while(cur)
{
nums.push_back(cur->val);
cur=cur->next;
}
return helper(nums,0,nums.size()-1);
}
TreeNode* helper(vector<int>& nums,int left,int right)
{
if(left>right) return NULL;
int mid=(left+right)/2;
TreeNode* cur=new TreeNode(nums[mid]);
cur->left=helper(nums,left,mid-1);
cur->right=helper(nums,mid+1,right);
return cur;
}
};