思路:
- 最简单的做法就是先把链表中的值按序存入一个vector中,然后通过简单的二分来找到子树的根结点,然后用递归把它们都构建成一棵树即可。
代码:
/**
* 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:
vector<int> temp;
TreeNode* build(int l,int r)
{
if(l==r)
return NULL;
int mid=l+r>>1;
TreeNode* root=new TreeNode(temp[mid]);
root->left=build(l,mid);
root->right=build(mid+1,r);
return root;
}
TreeNode* sortedListToBST(ListNode* head) {
ListNode *h=head;
while(h)
{
temp.push_back(h->val);
h=h->next;
}
return build(0,temp.size());
}
};