题目描述:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Example
题目思路:
2
1->2->3 => / \
1 3
这题就是永远以中间的node为root,然后左子树为剩下的左边list组成的bst,右子树为剩下的右边list组成的bst。
Mycode(AC = 85ms):
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: a tree node
*/
TreeNode *sortedListToBST(ListNode *head) {
// write your code here
if (head == NULL) {
return NULL;
}
if (head->next == NULL) {
return new TreeNode(head->val);
}
// find the length of list
int len = 0;
ListNode *fast = head;
while (fast) {
fast = fast->next;
len++;
}
// find the middle of list
ListNode *slow = head;
len = len / 2;
while (len > 1) {
slow = slow->next;
len--;
}
// left tree is built by left list;
// right tree is built by right list
ListNode *head2 = slow->next->next;
TreeNode *root = new TreeNode(slow->next->val);
slow->next = NULL;
root->left = sortedListToBST(head);
root->right = sortedListToBST(head2);
return root;
}
};