Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
给定一元素已经排好序的链表,将其转化为二叉查找树,只要根据二叉查找树的定义,用递归方法求解即可。为了方便求解,首先将链表的元素存到数组中。算法的时间复杂度为O(logn)。
/**
* 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> nums;
while(head)
{
nums.push_back(head->val);
head=head->next;
}
return STB(nums,0,nums.size()-1);
}
TreeNode* STB(vector<int>& nums,int low,int high)
{
if(high<low)
return NULL;
int mid=low+(high-low)/2;
TreeNode* root=new TreeNode(nums[mid]);
root->left=STB(nums,low,mid-1);
root->right=STB(nums,mid+1,high);
return root;
}
};