jayati

Convert Sorted List to Binary Search Tree

Mar 11th, 2023
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode() : val(0), next(nullptr) {}
  7.  *     ListNode(int x) : val(x), next(nullptr) {}
  8.  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
  9.  * };
  10.  */
  11. /**
  12.  * Definition for a binary tree node.
  13.  * struct TreeNode {
  14.  *     int val;
  15.  *     TreeNode *left;
  16.  *     TreeNode *right;
  17.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
  18.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  19.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  20.  * };
  21.  */
  22. class Solution {
  23. public:
  24.     TreeNode* constructBST(ListNode *leftHead, ListNode *rightHead) {
  25.         if (leftHead == rightHead)
  26.             return nullptr;
  27.         ListNode *slow = leftHead, *fast = leftHead;
  28.         while (fast != rightHead && fast -> next != rightHead) {
  29.             slow = slow -> next;
  30.             fast = fast -> next -> next;
  31.         }
  32.         TreeNode *root = new TreeNode(slow -> val);
  33.         root -> left = constructBST(leftHead, slow);
  34.         root -> right = constructBST(slow -> next, rightHead);
  35.         return root;
  36.     }
  37.     TreeNode* sortedListToBST(ListNode* head) {
  38.         if (head == nullptr)
  39.             return nullptr;
  40.         if (head -> next == nullptr) {
  41.             TreeNode *root = new TreeNode(head -> val);
  42.             return root;
  43.         }
  44.         return constructBST(head, nullptr);
  45.     }
  46. };
Advertisement
Add Comment
Please, Sign In to add comment