109. Convert Sorted List to Binary Search Tree(Leetcode每日一题-2020.08.18)

Problem

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

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Constraints:

  • The numner of nodes in head is in the range [0, 2 * 10^4].
  • 10^5 <= Node.val <= 10^5

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Example1

109. Convert Sorted List to Binary Search Tree(Leetcode每日一题-2020.08.18)_第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.

Example2

Input: head = []
Output: []

Example3

Input: head = [0]
Output: [0]

Example4

Input: head = [1,3]
Output: [3,1]

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        if(!head)
            return NULL;
        
        int len = 0;
        ListNode *cur = head;
        while(cur) //计算链表长度
        {
            len++;
            cur = cur->next;
        }

        if(len == 1)
            return new TreeNode(head->val);

        ListNode *mid_prev = head; //找到中间节点的前一个节点
        for(int i = 0;i<len/2-1;++i)
            mid_prev = mid_prev->next;

        ListNode *mid = mid_prev->next;
        mid_prev->next = NULL;//断开前半段链表
       

        TreeNode *root = new TreeNode(mid->val);
        root->left = sortedListToBST(head);
        root->right = sortedListToBST(mid->next);
    
        return root;

        
        
    }
};

你可能感兴趣的:(leetcode链表)