原题
原题
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
分析
将一个排好序的链表转化成一个平衡二叉查找树。
因为链表的特殊构造,我们不能够随机访问链表的中间元素,因此,需要有一些其他的考虑。
考虑二叉树的中序遍历:
inorder(TreeNode * root)
{
if(root==NULL)
return;
inorder(root->left);
visit();
inorder(root->right);
}
对于BST来说,中序遍历是一个有序的序列,因此,可以按照这个规律构造BST:
class Solution {
private:
int counts(ListNode*head)//统计有多少个节点
{
ListNode*p=head;
int count=0;
while(NULL!=p)
{
++count;
p=p->next;
}
return count;
}
TreeNode* helper(int n,ListNode*&head)
{
if (0==n)
return NULL;
TreeNode*root=new TreeNode(0);
root->left=helper(n/2,head);
root->val=head->val;
head=head->next;
root->right=helper(n-n/2-1);
return root;
}
public:
TreeNode* sortedListToBST(ListNode* head) {
int n =counts(head);
return helper(n,head);
}
};
参考:
https://discuss.leetcode.com/topic/3286/share-my-code-with-o-n-time-and-o-1-space/2