Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
/**
* 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 * CreateNode(vector<int>&vals,int start,int end){
if(start>end)return NULL;
int mid=(start+end)/2;
TreeNode* ret=new TreeNode(vals[mid]);
ret->left=CreateNode(vals,start,mid-1);
ret->right=CreateNode(vals,mid+1,end);
}
TreeNode *sortedListToBST(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> values;
while(head!=NULL){
values.push_back(head->val);
head=head->next;
}
return CreateNode(values,0,values.size()-1);
}
};
本文介绍了一种将升序排列的单链表转换为高度平衡的二叉搜索树的方法。通过先将链表元素存储到数组中,再利用递归的方式创建平衡的二叉树节点。

被折叠的 条评论
为什么被折叠?



