Sunday, April 19, 2020

109. 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.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted linked list: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

/**
 * 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) {
        ListNode *slow = head;
        ListNode *fast = head;
        ListNode *prev = NULL;
        if (head == NULL) {
            return NULL;
        }

        while (fast != NULL && fast -> next != NULL) {
            prev = slow;
            slow = slow -> next;
            fast = fast -> next -> next;
        }
        ListNode *secondHalf = slow -> next;
        slow -> next = NULL;
        TreeNode *root = new TreeNode(slow -> val);
        if (prev != NULL) {
            prev -> next = NULL;
        } else {
            return root;
        }
        root -> left = sortedListToBST(head);
        root -> right = sortedListToBST(secondHalf);
        return root;
    }
};
class Solution {
public:
    
    
    TreeNode* listToBST(ListNode *head){
        
        if(head==NULL)
            return NULL;
        TreeNode *root;
        ListNode *slow, *fast, *prev_slow, *temp;
        slow = head;
        fast = head;
        prev_slow = head;
        temp = head;
        
        while(fast!=NULL&&fast->next!=NULL){
            fast = fast->next->next;
            prev_slow = slow;
            slow = slow->next;
        }
        
        
        
        
        if(slow==fast){   
            root = new TreeNode(head->val);
            return root;
        }
        else if(fast==NULL){
            root = new TreeNode(slow->val);
            prev_slow->next = NULL;
            root->left = listToBST(head);
            root->right = listToBST(slow->next);
        }else{
             root = new TreeNode(slow->val);
            slow = slow->next;
            prev_slow->next = NULL;
            root->left = listToBST(head);
            root->right = listToBST(slow);
        }
        return root;
        
        
    }
    
    TreeNode* sortedListToBST(ListNode* head) {
  
        return listToBST(head);
        
    }
};

No comments:

Post a Comment