Created
August 14, 2014 06:26
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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