由于单链表是升序的,我们就可以将此问题化简成把中间节点左边建成左子树,中间节点有半部分建成右子树的两个子问题(递归解决),但是这里非常要注意,我们不能像数组一样,那样的跑不过测试用例,(至于为什么,我还不知道,请大家为我解答)我们可以将链表断开形成两个单链表,在组装在一起就好了。
* 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;
}
if(head->next==NULL){
return new TreeNode(head->val);
}
ListNode* fast=head;
ListNode* slow=head;
ListNode* pre=NULL;
while(fast&&fast->next){
pre=slow;
fast=fast->next->next;
slow=slow->next;
}
TreeNode* root=new TreeNode(slow->val);
pre->next=NULL;//将链表断开形成两个新链表
root->left=sortedListToBST(head);
root->right=sortedListToBST(slow->next);
return root;
}
};