每日题解:LeetCode 109. 有序链表转换二叉搜索树
题目描述
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
解法
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if (head == nullptr)
return nullptr;
if (head->next == nullptr)
return new TreeNode(head->val);
ListNode* slow = head, *fast = head, *pre = nullptr;
while (fast != nullptr && fast->next != nullptr) {
pre = slow;
slow = slow->next;
fast = fast->next->next;
}
pre->next = nullptr;
TreeNode* node = new TreeNode(slow->val);
node->left = sortedListToBST(head);
node->right = sortedListToBST(slow->next);
return node;
}
};
解题思路
快慢指针
题目要求构建一个二叉搜索树,即
1、二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1
2、提供的单链表,其中的元素按升序排序
需要找到一个根节点,保证其左右子树的节点个数尽可能接近,那么寻找链表的中点最为合适;
寻找链表的中点,那么快慢指针比较合适
if (head == nullptr)
return nullptr;
if (head->next == nullptr)
return new TreeNode(head->val);
ListNode* slow = head, *fast = head, *pre = nullptr;
while (fast != nullptr && fast->next != nullptr) {
pre = slow;
slow = slow->next;
fast = fast->next->next;
}
//将链表断开,分为左右两个子树,这里不断开,会超时
pre->next = nullptr;
其中有个关键的地方pre->next = nullptr;
,需要将链表分成两个部分,避免后面的递归无法结束
接下来就是构造二叉搜索树
TreeNode* node = new TreeNode(slow->val);
node->left = sortedListToBST(head);
node->right = sortedListToBST(slow->next);
return node;