題目
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
解題之法
/**
* 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;
if (!head->next) return new TreeNode(head->val);
ListNode *slow = head;
ListNode *fast = head;
ListNode *last = slow;
while (fast->next && fast->next->next) {
last = slow;
slow = slow->next;
fast = fast->next->next;
}
fast = slow->next;
last->next = NULL;
TreeNode *cur = new TreeNode(slow->val);
if (head != slow) cur->left = sortedListToBST(head);
cur->right = sortedListToBST(fast);
return cur;
}
};
分析
這道題是要求把有序鏈表轉(zhuǎn)為二叉搜索樹(shù),和之前那道Convert Sorted Array to Binary Search Tree 將有序數(shù)組轉(zhuǎn)為二叉搜索樹(shù)思路完全一樣,只不過(guò)是操作的數(shù)據(jù)類(lèi)型有所差別,一個(gè)是數(shù)組,一個(gè)是鏈表。
數(shù)組方便就方便在可以通過(guò)index直接訪問(wèn)任意一個(gè)元素,而鏈表不行。由于二分查找法每次需要找到中點(diǎn),而鏈表的查找中間點(diǎn)可以通過(guò)快慢指針來(lái)操作。
找到中點(diǎn)后,要以中點(diǎn)的值建立一個(gè)數(shù)的根節(jié)點(diǎn),然后需要把原鏈表斷開(kāi),分為前后兩個(gè)鏈表,都不能包含原中節(jié)點(diǎn),然后再分別對(duì)這兩個(gè)鏈表遞歸調(diào)用原函數(shù),分別連上左右子節(jié)點(diǎn)即可。