LeetCode: Convert Sorted List to Binary Search Tree

本文介绍了一种通过递归方法将有序链表转换为高度平衡二叉搜索树的技术,时间复杂度为O(n),并详细解释了平衡二叉搜索树的概念及其构建过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

For example,
Given list {9,12,14,17,19,23,50,54,67,72,76},
the below BST is one possible solution.

An example of a height-balanced tree. A height-balanced tree is a tree whose subtrees differ in height by no more than one and the subtrees are height-balanced, too.

利用递归,从低向上建立平衡二叉搜索树,时间复杂度为O(n)。

/**
 * 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 *convert(ListNode* &head, int nStart, int nEnd)
    {
        if (nStart > nEnd) return NULL;
        
        int mid = nStart + (nEnd-nStart)/2;
        TreeNode* left = convert(head, nStart, mid-1);
        TreeNode* parent = new TreeNode(head->val);
        parent->left = left;
        head = head->next;
        parent->right = convert(head, mid+1, nEnd);
        return parent;
    }
    
    TreeNode *sortedListToBST(ListNode *head) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (head == NULL) return NULL;
        int nSize = 1;
        ListNode* ptr = head;
        while (ptr->next != NULL)
        {
            ptr = ptr->next;
            ++nSize;
        }
        return convert(head, 0, nSize-1);
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值