LeetCode-109. 有序链表转换二叉搜索树

题目描述 有序链表转换二叉搜索树

给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

示例

给定的有序链表: [-10, -3, 0, 5, 9],

一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:

解题思路

拿到题目想的是先把链表中的值存在一个vector中,然后递归创建二叉搜索树。菜鸡什么时候才能成长啊,心累ing。
做完后借鉴大佬们的想法,用快慢指针来找到链表的中间节点,然后递归调用原函数。

代码

class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        if(!head) return nullptr;
        vector<int> nums;
        while(head){
            nums.push_back(head->val);
            head = head->next;
        }
        TreeNode *root = new TreeNode(nums[nums.size()/2]);
        root->left = sortedListToBST(nums, 0, nums.size()/2-1);
        root->right = sortedListToBST(nums, nums.size()/2+1, nums.size()-1);
        return root;
    }

    TreeNode* sortedListToBST(vector<int> nums, int i, int j) {
        if(i>j) return nullptr;
        int x = (i+j)/2;
        TreeNode *root = new TreeNode(nums[x]);
        root->left = sortedListToBST(nums, i, x-1);
        root->right = sortedListToBST(nums, x+1, j);
        return root;
    }

};

大佬们的代码,宝宝什么时候才能学会呀。

class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        if (!head) return nullptr;
        ListNode* fast = head, *slow = head, *pre = nullptr;
        while (fast && fast->next){
            pre = slow;
            fast = fast->next->next;
            slow = slow->next;
        }
        TreeNode* root = new TreeNode(slow->val);
        if (pre){
            pre->next = nullptr;
            root->left = sortedListToBST(head);
            root->right = sortedListToBST(slow->next);
        }
        return root;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容