Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted linked list: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 0 / \ -3 9 / / -10 5
第一种方法:链表转化为数组
先把链表中的每一个value存到数组arr中,然后用二分查找,(开头+结尾)/2 = 中点,arr[中点]则是当前根结点的value。左子树则是从 BSP(开头,中点-1),右子树则是BSP(中点+1,结尾)。
这种方法可以得到正确的答案,但是如果测试数据过大就会超出内存限制。因为数组arr的大小有限制,所以数据很大的时候arr不能存下所有数据。也就是这题不能用先转化为数组来做。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
vector<int> arr;
while(head)
{
arr.push_back(head->val);
head = head->next;
}
// TreeNode* root = new TreeNode(0);
return BST(0,arr.size()-1,arr);
}
TreeNode* BST(int m,int n,vector<int> arr)
{
if(m>n)
return 0;
int mid = (m+n+1)/2;
TreeNode* root = new TreeNode(8);
root->val = arr[mid];
root->left = BST(m,mid-1,arr);
root->right= BST(mid+1,n,arr);
return root;
}
};
第二种方法:直接把链表转化为二叉树
这种方法的难点在于,如何找到二叉树的根结点的值?也就是链表的中点如何找到?可以设置两个指针,指针a和指针b都指向链表头,指针a每次向next移动一次(也就是a =a->next),而指针b每次向next移动两次(也就是b = b->next->next)。这么一来,a和b同时从链表头head开始,当b移动到结尾的时候,a刚好移动到链表的中点(因为a每次移动都是b的一半)。根结点的值算出来之后,就把链表分成两半。前一半就是从链表头head到中点,后一半就是从中点到结尾。左子树的值同样的求法,左子树的值就是前一半链表的中点,右子树的值就是后一半链表的中点。(备注:这种方法可以通过)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
return BST(head);
}
TreeNode* BST(ListNode* head)
{
if(!head||!head->next)
{
if(head)
{
TreeNode* temp = new TreeNode(0);
temp->val = head->val;
return temp;
}
return NULL;
}
ListNode* curr = head;
ListNode* s = head;
ListNode* fast = head->next->next;
while(fast&&fast->next)
{
s = s->next;
fast = fast->next->next;
}
TreeNode* root = new TreeNode(0);
root->val = s->next->val;
if(s->next)
root->right = BST(s->next->next);
s->next = NULL;
root->left = BST(head);
return root;
}
};