Convert Sorted List to BST | LeetCode 109 | Google Coding Interview Question

preview_player
Показать описание


#leetcode #datastructure #algorithm #coding #codinginterview #googlecodinginterview
Рекомендации по теме
Комментарии
Автор

same approach as 108 Leetcode, but it's great idea :) Thanks

voquangaiviet
Автор

please check this, I'm getting error

TreeNode* sortedListToBST(ListNode* head) {
ListNode* slow=head;
ListNode*fast=head;
if(head==NULL){
return NULL;
}
if(head->next==NULL){
return new TreeNode(head->val);
}
while(fast!=NULL && fast->next!=NULL){
fast=fast->next->next;
slow=slow->next;
}
TreeNode*ans=new TreeNode(slow->val);



return ans;

}

halchal
Автор

hey thank you for the video. can you explain again why mid.next needs to be null? wont the mid be re-declared at every recursion?

yanchengpan
Автор

class Solution {
public:

TreeNode* sortedListToBST(ListNode* head) {
//base cases:
if(head==NULL) return NULL;
if(head->next==NULL) return new TreeNode(head->val);
ListNode* prev= NULL;
ListNode* slow=head;
ListNode* fast=head;
ListNode* mid=NULL;
while(fast != NULL && fast->next != NULL) {
fast=fast->next->next;
prev=slow;
slow=slow->next;

}
mid= slow;
prev->next=NULL;
TreeNode* root= new TreeNode(mid->val);
root->left= sortedListToBST(head);
root->right= sortedListToBST(mid->next);

return root;

}
};

SadhanaSharma