跳转至

109.Convert Sorted List to Binary Search Tree

Tags: Medium Tree Linked List Depth-first Search

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


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

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        std::ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);

        if (!head) return NULL;

        ListNode *dummy = new ListNode(-1);
        dummy -> next = head;
        ListNode *pre = dummy;
        ListNode *slow = head, *fast = head;
        while (fast && fast -> next) {
            pre = pre -> next;
            slow = slow -> next;
            fast = fast -> next -> next;
        }
        pre -> next = NULL; //断开建立左子树
        fast = slow -> next; //右子树的起始
        slow -> next = NULL;

        TreeNode *root = new TreeNode(slow -> val);
        TreeNode *l = sortedListToBST(dummy -> next);
        TreeNode *r = sortedListToBST(fast);
        root -> left = l; root -> right = r;

        return root;
    }
};

快慢指针,递归求解。