5 Convert Sorted List to Binary Search Tree_Leetcode

时间:2023-03-08 17:20:43

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

这题和sort list等题都比较相似,需要先用快慢指针的方法找到链表的中点,然后用recursive的方式构建左子树和右子树(用到的思想是Divide&Conquer),然后再构建好这个节点。

编程时一点要注意:

(1)dummy节点的使用可以帮助找到中点的prev节点

但是dummy节点只有当用时再构造,建议不要提前建好当参数传进来,会非常不清晰。用完后最后记得delete,否则会memory leak. 也不能delete得过早,因为prev可能等于dummy.

(2)边界情况

当middle节点为head时,应注意,左子树为NULL,不要递归build。

Code:

/**
* 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) return NULL;
TreeNode* treeHead = buildTree(head);
return treeHead;
} TreeNode* buildTree(ListNode *head)
{
if(!head) return NULL;
if(!head->next) return new TreeNode(head->val); ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* prev = dummy, *slow = dummy->next, *fast = dummy->next->next;
while(fast && fast->next)
{
slow = slow->next;
prev = prev->next;
fast = fast->next->next;
} TreeNode* cur = new TreeNode(slow->val); TreeNode* left, *right; // second error, cannot initialize left in the if-else
right = buildTree(slow->next);
if(prev != dummy) // first error
{
prev->next = NULL;
left = buildTree(head);
}
else left = NULL; cur->left = left;
cur->right = right; delete dummy; // first error, can not delete dummy too early if prev equals dummy return cur;
}
};