Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted linked list: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 0 / \ -3 9 / / -10 5
这个递归是自己写的,开心。基本思路是打断链表,每次找到中间节点,然后用递归继续做。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* 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 == NULL) return NULL;
TreeNode *mid = new TreeNode(0);
if (head -> next == NULL){
mid -> val = head -> val;
//cout << mid->val << endl;
return mid;
}
ListNode* slow = head , *fast = head, *tmp = NULL;
while(fast->next!=NULL && fast->next->next!=NULL){
tmp = slow;
slow = slow->next;
fast = fast->next->next;
}
// ListNode * last = head;
// for (ListNode *tmp = head;tmp!=slow;tmp = tmp->next){
// last = tmp;
// }
mid -> val = slow ->val;
ListNode * right = slow->next;
if (tmp == NULL){
head = NULL;
}
else{
tmp -> next = NULL;
}
// last -> next = NULL;
mid -> left = sortedListToBST(head);
mid -> right = sortedListToBST(right);
return mid;
}
};
注释了是我之前的打断方法,现在看了别人的解决方案,用了相当于快,慢,超慢三指针的解决方案,还可以哈。