题目描述
给定一个单链表,其中的元素按升序排序,请将它转化成平衡二叉搜索树(BST)
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
思路:
- 本题考查把有序单链表转换成平衡二叉搜索树(二叉排序树、二叉查找树),类似于将有序数组转换成平衡二叉搜索树,我们需要找到链表的中值,然后递归 的构建平衡二叉搜索树;
- 找链表中值的方法可以使用快慢指针的方法;
- 在递归时要注意需要把原链表拆断,舍弃中间节点然后继续递归;
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for binary tree
* 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 == nullptr)
return nullptr;
TreeNode *root = new TreeNode(0);
BSTHelper(root, head);
return root;
}
void BSTHelper(TreeNode *node, ListNode *head)
{
ListNode *fast = head;
ListNode *low = head;
ListNode *prelow;
while (fast != nullptr && fast->next != nullptr)
{
fast = fast->next->next;
prelow = low;
low = low->next;
}
node->val = low->val;
if (low != head)
{
prelow->next = nullptr;
node->left = new TreeNode(0);
BSTHelper(node->left, head);
}
if (low->next != nullptr)
{
ListNode *tmp = low->next;
low->next = nullptr;
node->right = new TreeNode(0);
BSTHelper(node->right, tmp);
}
return;
}
};
代码没有很简洁,但是思路很清晰,简洁版的如下:
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
if (head == nullptr) return nullptr;
if (head->next == nullptr) return new TreeNode(head->val);
ListNode dummy = ListNode(0);
dummy.next = head;
ListNode* p2 = &dummy;
ListNode* p1 = &dummy;
while (p2->next&&p2->next->next) {
p2 = p2->next->next;
p1 = p1->next;
}
TreeNode *root = new TreeNode(p1->next->val);
p2 = p1->next->next;
p1->next = nullptr;
root->left = sortedListToBST(dummy.next);
root->right = sortedListToBST(p2);
return root;
}
};