Leetcode 109. Convert Sorted List to Binary Search Tree (Medium) (cpp)
Tag: Linked List, Depth-first Search
Difficulty: Medium
/*
109. Convert Sorted List to Binary Search Tree (Medium)
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 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) {
TreeNode *fake = new TreeNode(-1);
if (head == NULL) {
return fake -> left;
}else if (head -> next == NULL) {
fake -> val = head -> val;
return fake;
}
ListNode *fast = head, *slow = head, *slow_prev = NULL;
while (fast -> next != NULL && fast -> next -> next != NULL) {
slow_prev = slow;
slow = slow -> next;
fast = fast -> next -> next;
}
fake -> val = slow -> val;
if (slow_prev != NULL) {
slow_prev -> next = NULL;
fake -> left = sortedListToBST(head);
}
fake -> right = sortedListToBST(slow -> next);
return fake;
}
};