109. Convert Sorted List to Binary Search Tree**

109. Convert Sorted List to Binary Search Tree**

https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/

Title Description

Given 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.

Example:

Given the sorted linked list: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

C ++ implementation 1

In order to produce a balanced BST, you can find each row in the intermediate node as the root node.

The following practices for using the value of the node vector save the list.

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

2 in C ++

The midpoint speed using a pointer to find the list noted that the following code is directed dummy slow start, and if the list is 1 -> 2 -> NULL, i.e., the case where only two nodes, it will point to a slow but not 2, after use slow-> next to give 2, i.e., the root node. SLOW final point before a root node.

class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        if (!head)
            return nullptr;

        ListNode *dummy  = new ListNode(0);
        dummy->next = head;
        // slow 最终指向根节点前一个节点
        ListNode *slow = dummy, *fast = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
        }
        // slow->next 存在, 即根节点存在, 那么可以获得根节点的右边的节点
      	// slow->next->next, 并以它开始构建右子树.
        TreeNode *root = new TreeNode(slow->next->val);
        root->right = sortedListToBST(slow->next->next);
        // 这里不要忘了将前半段链表的结尾设为 NULL.
        slow->next = nullptr;
        root->left = sortedListToBST(dummy->next);
        return root;
    }
};
Published 455 original articles · won praise 8 · views 20000 +

Guess you like

Origin blog.csdn.net/Eric_1993/article/details/104965933