Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save pdu/4448509 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4448509 to your computer and use it in GitHub Desktop.
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. http://leetcode.com/onlinejudge
/**
* 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:
int get_list_num_(ListNode* head) {
int ret = 0;
while (head) {
ret++;
head = head->next;
}
return ret;
}
ListNode* get_list_mid_(ListNode* head, int n) {
int mid = (n - 1) / 2;
while (mid--)
head = head->next;
return head;
}
TreeNode* get_bst_(ListNode* head, int n) {
if (n == 0) {
return NULL;
}
ListNode* mid = get_list_mid_(head, n);
int mid_idx = (n + 1) / 2;
TreeNode* node = new TreeNode(mid->val);
node->left = get_bst_(head, mid_idx - 1);
node->right = get_bst_(mid->next, n - mid_idx);
return node;
}
TreeNode *sortedListToBST(ListNode *head) {
int n = get_list_num_(head);
return get_bst_(head, n);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment