Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For example,
Given list {9,12,14,17,19,23,50,54,67,72,76}
,
the below BST is one possible solution.
An example of a height-balanced tree. A height-balanced tree is a tree whose subtrees differ in height by no more than one and the subtrees are height-balanced, too.
利用递归,从低向上建立平衡二叉搜索树,时间复杂度为O(n)。
/**
* 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 *convert(ListNode* &head, int nStart, int nEnd)
{
if (nStart > nEnd) return NULL;
int mid = nStart + (nEnd-nStart)/2;
TreeNode* left = convert(head, nStart, mid-1);
TreeNode* parent = new TreeNode(head->val);
parent->left = left;
head = head->next;
parent->right = convert(head, mid+1, nEnd);
return parent;
}
TreeNode *sortedListToBST(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (head == NULL) return NULL;
int nSize = 1;
ListNode* ptr = head;
while (ptr->next != NULL)
{
ptr = ptr->next;
++nSize;
}
return convert(head, 0, nSize-1);
}
};