Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
http://www.lintcode.com/en/problem/convert-sorted-list-to-balanced-bst/#
用快慢指针找出中点,作为根,中点左右两边分别递归的构建二叉树。
最初使用跟Sort List一般的方法:一个链分裂成两个链,发现有错误。原因是有中点需要去掉,跟划分链不完全一致了。
最好是使用一个begin指针指示第一个元素,end指针指示最后一个元素的下一个位置(即左闭右开空间),很方便的就构建起平衡二叉树。
元素个数为奇数的构建平衡二叉查找树很容易理解。
元素个数为偶数的构建平衡二叉查找树应该是这样的:
/**
* 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 *buildTree(ListNode *begin,ListNode *end){
if(begin==end){
return NULL;
}
ListNode *faster=begin;
ListNode *slower=begin;
while(faster->next!=end && faster->next->next!=end){
faster=faster->next->next;
slower=slower->next;
}
faster=slower->next;
TreeNode *root=new TreeNode(slower->val);
root->left=buildTree(begin,slower);
root->right=buildTree(faster,end);
return root;
}
TreeNode *sortedListToBST(ListNode *head) {
// write your code here
if(head==NULL){
return NULL;
}
if(head->next==NULL){
return new TreeNode(head->val);
}
return buildTree(head,NULL);
}
};