• LeetCode //C - 109. Convert Sorted List to Binary Search Tree


    109. Convert Sorted List to Binary Search Tree

    Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height-balanced binary search tree.
     

    Example 1:

    在这里插入图片描述

    Input: head = [-10,-3,0,5,9]
    Output: [0,-3,9,-10,null,5]
    Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.

    Example 2:

    Input: head = []
    Output: []

    Constraints:
    • The number of nodes in head is in the range [ 0 , 2 ∗ 1 0 4 ] [0, 2 * 10^4] [0,2104].
    • − 1 0 5 < = N o d e . v a l < = 1 0 5 -10^5 <= Node.val <= 10^5 105<=Node.val<=105

    From: LeetCode
    Link: 109. Convert Sorted List to Binary Search Tree


    Solution:

    Ideas:
    1. Find the Middle Element: The middle element of the sorted linked list will be the root of the BST. The left half of the list will form the left subtree, and the right half will form the right subtree.
    2. Recursive Approach: Use recursion to build the tree. For each recursive call, find the middle of the current segment of the linked list, create a tree node, and recursively build the left and right subtrees.
    Code:
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
     * };
     */
    struct TreeNode* createTreeNode(int val) {
        struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
        newNode->val = val;
        newNode->left = NULL;
        newNode->right = NULL;
        return newNode;
    }
    
    // Helper function to find the middle element of the linked list.
    struct ListNode* findMiddleElement(struct ListNode* head) {
        struct ListNode* prevPtr = NULL;
        struct ListNode* slowPtr = head;
        struct ListNode* fastPtr = head;
        
        // Move fastPtr by 2 and slowPtr by 1
        while (fastPtr != NULL && fastPtr->next != NULL) {
            prevPtr = slowPtr;
            slowPtr = slowPtr->next;
            fastPtr = fastPtr->next->next;
        }
        
        // Handling the case when slowPtr might be the head
        if (prevPtr != NULL) {
            prevPtr->next = NULL;
        }
        
        return slowPtr;
    }
    
    struct TreeNode* sortedListToBST(struct ListNode* head) {
        // Base case
        if (head == NULL) {
            return NULL;
        }
        
        // Find the middle element of the linked list
        struct ListNode* mid = findMiddleElement(head);
        
        // The middle element becomes the root
        struct TreeNode* node = createTreeNode(mid->val);
        
        // Base case when there is just one element in the linked list
        if (head == mid) {
            return node;
        }
        
        // Recursively construct the left subtree and right subtree
        node->left = sortedListToBST(head);
        node->right = sortedListToBST(mid->next);
        
        return node;
    }
    
    // Function to print the tree in order for testing
    void inorderTraversal(struct TreeNode* root) {
        if (root == NULL) {
            return;
        }
        inorderTraversal(root->left);
        printf("%d ", root->val);
        inorderTraversal(root->right);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
  • 相关阅读:
    OpenTiny Vue 组件库支持 Vue2.7 啦!
    IDEA的Facets添加web后没有反应
    新火种AI|苹果要将苹果智能做成AI时代的APP Store?
    Gin,Gorm实现Web计算器
    Java项目:SSM在线租房售房平台多城市版本
    Springboot(六):mysql配置及数据库查询 | 超级详细,建议收藏
    【Git技巧】第三篇 删除冗余的本地或远程的操作分支
    文档管理控件Aspose.total for.NET 迎来重大更新,全新版本v22.7全新版本来袭,快来看看都有哪些~
    动能方案 | 15693协议的读卡器应用 DP1363F 替代RC663
    数据结构之链表详解(1)
  • 原文地址:https://blog.csdn.net/navicheung/article/details/139036237