/**
* 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) {}
* };
*/
//bottom-up approach to build the binary search tree
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(head==NULL)
return NULL;
int n=0;
ListNode* h=head;
while(head){
head=head->next;
++n;
}
return helper(h,0,n-1);
}
TreeNode* helper(ListNode* &head,int start,int end){
if(start>end)
return NULL;
int mid=start+(end-start)/2;
TreeNode* left=helper(head,start,mid-1);
TreeNode* parent=new TreeNode(head->val);
parent->left=left;
head=head->next;
parent->right=helper(head,mid+1,end);
return parent;
}
};
Leetcode: Convert Sorted List to Balanced Binary Search Tree
最新推荐文章于 2021-05-04 07:30:25 发布