109 - Convert Sorted List to Binary Search Tree

本文详细介绍了如何通过计算链表长度并递归地找到中间节点来将排序单链表转换为高度平衡的二叉搜索树(BST)。此过程涉及链表操作、递归技巧和理解BST的性质。

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

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

Subscribe to see which companies asked this question

思路分析:

这题的关键是能找出当前链表的中间节点,然后再递归左右的子链表,开始的时候程序先计算链表总厂,然后传入两个前后索引指针,最后每次递归找出中间节点即可。

/**
 * 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:
    int calLen(ListNode *node)
    {
        int len = 0;
        while(node)
        {
            len++;
            node = node->next;
        }
        return len;
    }
    
    TreeNode *createTree(ListNode *node, int left, int right)
    {
        if (left > right)
            return NULL;
            
        int mid = (left + right) / 2;
        
        ListNode *p = node;
        
        for(int i = left; i < mid; i++)
            p = p->next;
            
        TreeNode *leftNode = createTree(node, left, mid - 1);
        TreeNode *rightNode = createTree(p->next, mid + 1, right);
        
        TreeNode *tNode = new TreeNode(p->val);
        
        tNode->left = leftNode;
        tNode->right = rightNode;
        
        return tNode;        
    }
    
    TreeNode *sortedListToBST(ListNode *head) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int len = calLen(head);
        return createTree(head, 0, len - 1);
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值