[InterviewBit] Convert Sorted List to Binary Search Tree

Convert Sorted List to Binary Search Tree

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* cut(ListNode* A) {
ListNode* slow = A;
ListNode* fast = A;
ListNode* prev = slow;
while(fast->next and fast->next->next) {
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
return prev;
}
TreeNode* Solution::sortedListToBST(ListNode* A) {
if(A == NULL) return NULL;
if(A->next == NULL) return new TreeNode(A->val);
ListNode* now = cut(A);
TreeNode* res = new TreeNode(now->next->val);
ListNode* right = now->next->next;
ListNode* left = A;
now->next->next = NULL;
now->next = NULL;
res->left = sortedListToBST(left);
if(right != NULL) res->right = sortedListToBST(right);
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/03/PS/interviewbit/convert-sorted-list-to-binary-search-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.