LeetCode109—Convert Sorted List to Binary Search Tree

本文介绍了一种将排序链表转换为高度平衡二叉搜索树(BST)的方法。利用链表特性和二叉树中序遍历原理,设计了一种O(n)时间复杂度和O(1)空间复杂度的解决方案。

原题

原题
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值