/*
Convert Sorted List to Binary Search Tree
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 *findMidNode(ListNode *head){
if(head==NULL) return NULL;
ListNode *prev = NULL;
ListNode *curr = head;
ListNode *tail = curr->next;
if(tail!=NULL) tail = tail->next;
while(tail!=NULL){
prev = curr;
curr = curr->next;
tail = tail->next;
if(tail!=NULL) tail = tail->next;
}
if(curr==NULL) return NULL;
TreeNode *node = new TreeNode(curr->val);
if(prev!=NULL) prev->next = NULL;
if(head!=curr) node->left = findMidNode(head);
node->right = findMidNode(curr->next);
return node;
}
TreeNode *sortedListToBST(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(head==NULL) return NULL;
if(head->next==NULL){
TreeNode* root = new TreeNode(head->val);
return root;
}
return findMidNode(head);
}
};
No comments:
Post a Comment