题目链接: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.
思路:这题的思路就是不断的二分链表,找到中点之后中点作为一个树结点,然后左边的递归构造左子树,右边的递归构造右子树。
刚开始不停的RE,因为我找到中点之后将中点后面的作为右子树,本身置为NULL,左边的作为左子树,然后就出了一堆问题,递归无法跳出。
代码如下:
/**
* 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));
ListNode *slow = head, *fast = head->next;
while(fast && fast->next && fast->next->next)
slow = slow->next, fast=fast->next->next;
fast = slow->next;
TreeNode *root = new TreeNode(fast->val);
fast = fast->next, slow->next = NULL;
root->left = sortedListToBST(head);
root->right = sortedListToBST(fast);
return root;
}
};