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

解题思路:

将一个排好序的链表变成一个平衡的二叉搜索树,我们可以采用分治法来做这道题目

使用快慢指针找到这个链表的中点,将链表分为3部分:左链表,中点,右链表。

记得做链表的最后一个节点要与中点断开。

中点建立为新的根节点,然后对左子链表和右子链表进行构造树。

代码:

/**
 * 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) {
        if(!head) return NULL;
        if(!head->next) return new TreeNode(head->val);
        
        
        //splict into 2 list
        ListNode *fast = head, *slow = head, *pre = NULL;
        while(fast && fast->next){
            fast = fast->next->next;
            pre = slow;
            slow = slow->next;
        }
        if(pre) pre->next = NULL;
        TreeNode* root = new TreeNode(slow->val);
        if(head != slow)root->left = sortedListToBST(head);
        root->right = sortedListToBST(slow->next);
        return root;
    }
};
原文地址:https://www.cnblogs.com/yaoyudadudu/p/9302760.html