这题起初自己写的,忘记记录中间节点的前面一个节点了,把中间节点算在左子树里面了,
所以一直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;
}
};
本文介绍了一种将有序链表转换为高度平衡二叉搜索树的方法。通过使用快慢指针找到中点,并以此作为根节点,递归地构造左右子树。文章附带实现代码。

被折叠的 条评论
为什么被折叠?



