Skip to content

Instantly share code, notes, and snippets.

@xiren-wang
Created August 14, 2014 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiren-wang/6203e9a9a487d5bba616 to your computer and use it in GitHub Desktop.
Save xiren-wang/6203e9a9a487d5bba616 to your computer and use it in GitHub Desktop.
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.
/**
* 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 *sortedListToBST(ListNode *head) {
if (!head)
return NULL;
//find middle to be root, then left(head), and right (root->next)
//Note: must cut off the left part, otherwise it's dead loop
ListNode *slow = head;
ListNode *prev = NULL;
ListNode *fast = slow->next; //1 -> 2: slow=1, fast=2, s=2, f=NULL; 1234: s=1, f=2; s=2; f=3, f=4
while(fast) {
prev = slow;
slow = slow->next;
fast = fast->next;
if (!fast)
break;
fast = fast->next;
}
TreeNode *root = new TreeNode (slow->val);
//cut off left part for left Child
if (prev)
prev->next = NULL;
if (slow == head)
root->left = NULL;
else
root->left = sortedListToBST(head);
root->right = sortedListToBST(slow->next);
return root;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment