- Convert Sorted List to Binary Search Tree
中文English
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Example
Example 1:
Input: array = [1,2,3]
Output:
2
/
1 3
Example 2:
Input: [2,3,6,7]
Output:
3
/
2 6
7
Explanation:
There may be multi answers, and you could return any of them.
解法1:思路:先用双指针找到中间节点,然后递归。时间复杂度O(nlogn)。
注意:这种有链表操作又有递归的情况代码并不好写,容易出错。需要特别仔细。
- 以p1为节点,但是p1从while出来后其前节点pre要保存下来。然后pre->next=NULL,这样就相当于把两个子链表断开了。要不然左子链表一直到整个链表结束才结束。
代码如下:
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param head: The first node of linked list.
* @return: a tree node
*/
TreeNode * sortedListToBST(ListNode * head) {
if (!head) return NULL;
return helper(head);
}
private:
TreeNode * helper(ListNode * head) {
if (!head) return NULL;
if (!head->next) return new TreeNode(head->val);
ListNode * p1 = head, * p2 = head, * pre = head;
while(p2 && p2->next) {
pre = p1;
p1 = p1->next;
p2 = p2->next->next;
}
//now p1 is the mid of the list;
TreeNode * mid = new TreeNode(p1->val);
pre->next = NULL;
mid->left = helper(head);
mid->right = helper(p1->next);
return mid;
}
};
稍微改了一下,这种写法也可以。
TreeNode * helper(ListNode * head) {
if (!head) return NULL;
if (!head->next) return new TreeNode(head->val);
ListNode * p1 = head, * p2 = head, * pre = head;
while(p2 && p2->next) {
pre = p1;
p1 = p1->next;
p2 = p2->next;
if (p2) p2 = p2->next;
}
//now p1 is the mid of the list;
TreeNode * mid = new TreeNode(p1->val);
pre->next = NULL;
mid->left = helper(head);
mid->right = helper(p1->next);
return mid;
}
这个写法也可以:以这个版本为准比较好。
TreeNode * helper(ListNode * head) {
if (!head) return NULL;
if (!head->next) return new TreeNode(head->val);
ListNode * p1 = head, * p2 = head->next, * pre = head;
while(p2) {
pre = p1;
p1 = p1->next;
p2 = p2->next;
if (p2) p2 = p2->next;
}
//now p1 is the mid of the list;
TreeNode * mid = new TreeNode(p1->val);
pre->next = NULL;
mid->left = helper(head);
mid->right = helper(p1->next);
return mid;
}