这题起初自己写的,忘记记录中间节点的前面一个节点了,把中间节点算在左子树里面了,
所以一直AC不了,后来看了别人写的发现要记录前面一个节点,才想起来自己搞错了,把中间节点
算在了左子树里面,其实很简单,具体看代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for binary tree
* 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)
return NULL;
if(!head->next)
return new TreeNode(head->val);
ListNode *fast,*slow,*pre=NULL;
fast=slow=head;
while(fast!=NULL&&fast->next!=NULL){
pre=slow;
fast=fast->next->next;
slow=slow->next;
}
TreeNode *tem=new TreeNode(slow->val);
pre->next=NULL;
tem->right=sortedListToBST(slow->next);
tem->left=sortedListToBST(head);
return tem;
}
};