題目
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)為二叉搜索樹看政,和之前那道Convert Sorted Array to Binary Search Tree 將有序數(shù)組轉(zhuǎn)為二叉搜索樹思路完全一樣祷肯,只不過是操作的數(shù)據(jù)類型有所差別泛鸟,一個是數(shù)組臭觉,一個是鏈表。
數(shù)組方便就方便在可以通過index直接訪問任意一個元素,而鏈表不行。由于二分查找法每次需要找到中點佛掖,而鏈表的查找中間點可以通過快慢指針來操作。
找到中點后涌庭,要以中點的值建立一個數(shù)的根節(jié)點芥被,然后需要把原鏈表斷開,分為前后兩個鏈表坐榆,都不能包含原中節(jié)點拴魄,然后再分別對這兩個鏈表遞歸調(diào)用原函數(shù),分別連上左右子節(jié)點即可席镀。