给出一个所有元素以升序排序的单链表,将它转换成一棵高度平衡的二分查找树
样例
样例 1:
输入: array = 1->2->3
输出:
2
/ \
1 3
样例 2:
输入: 2->3->6->7
输出:
3
/ \
2 6
\
7
解释:
可能会有多个符合要求的结果,返回任意一个即可。
/**
* 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) {
// write your code here
vector<int> tmp;
while(head)
{
tmp.push_back(head->val);
head=head->next;
}
if(tmp.empty()) return NULL;
TreeNode*newroot=builtree(tmp,0,tmp.size()-1);
return newroot;
}
TreeNode*builtree(vector<int>&A,int low,int high)
{
if(low>high) return NULL;
int mid=low+(high-low)/2;
TreeNode* newroot=new TreeNode(A[mid]);
newroot->left=builtree(A,low,mid-1);
newroot->right=builtree(A,mid+1,high);
return newroot;
}
};