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
The problem is quite interesting when limiting memory to O(1), and time complexity to O(n). In that way, extra array is forbidden. So
When there is only one node A, mid = A, NULL<-mid->NULL
When there are two node A, A+1, mid = A, NULL<-mid->A+1
When there are three node A, A+1, A+2, mid = A+1, A<-A+1->A+2
....
After building the tree, the pointer moves to the end. The code is like:
/**
* 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* BuildTree(ListNode*& head, int start, int end) {
if (start > end)
return NULL;
int mid = start + (end - start) / 2;
TreeNode* lChild = BuildTree(head, start, mid - 1);
TreeNode* parent = new TreeNode(head->val);
parent->left = lChild;
head = head->next;
TreeNode* rChild = BuildTree(head, mid + 1, end);
parent->right = rChild;
return parent;
}
TreeNode *sortedListToBST(ListNode *head) {
// Note: The Solution object is instantiated only once and is reused by each test case.
ListNode* p = head;
int len = 0;
while (p != NULL) {
len++;
p = p->next;
}
return BuildTree(head, 0, len-1);
}
};
I once wrote the function like:
TreeNode* BuildTree(ListNode* head, int start, int end)
which got wrong answer.
Python Version:
class Solution:
def CountLen(self, head):
sum = 0
while (head):
sum += 1
head = head.next
return sum
def ConvertToBST(self, head, start, end):
if (start > end or head == None):
return None, head
elif (start == end):
root = TreeNode(head.val)
head = head.next
return root,head
else:
mid = start + ((end-start)//2)
leftChild,head = self.ConvertToBST(head, start, mid-1)
root = TreeNode(head.val)
head = head.next
rightChild,head = self.ConvertToBST(head, mid+1, end)
root.left = leftChild
root.right = rightChild
return root,head
def sortedListToBST(self, head):
lens = self.CountLen(head)
root, head = self.ConvertToBST(head, 0, lens-1)
return root