给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree
类似题目 LeetCode 108. 将有序数组转换为二叉搜索树
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if(!head) return NULL;
ListNode *slow, *slow_pre, *fast;
slow = fast = head;
slow_pre = NULL;
while(fast && fast->next)
{
slow_pre = slow;
slow = slow->next;
fast = fast->next->next;
}
if(slow_pre)
slow_pre->next = NULL;//断开链表
if(slow && slow != head)
{
TreeNode *root = new TreeNode(slow->val);
root->left = sortedListToBST(head);
root->right = sortedListToBST(slow->next);
return root;
}
return new TreeNode(head->val);
}
};