Created
January 3, 2013 23:29
-
-
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
This file contains hidden or 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: | |
| 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