- 轉載請註明作者和出處:http://blog.csdn.net/u011475210
- 代碼地址:https://github.com/WordZzzz/Note/tree/master/LeetCode
- 刷題平臺:https://www.nowcoder.com/ta/leetcode
- 題 庫:Leetcode經典編程題
- 編 者:WordZzzz
題目描述
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
解題思路
升序鏈表轉換成高度平衡的二叉搜索樹,我們只需要找到鏈表的中點當作root然後左右遞歸就可以了。求鏈表中點當然還是用快慢指針了。
C++版代碼實現
/**
* 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) {
return toBST(head, NULL);
}
TreeNode *toBST(ListNode *head, ListNode *tail){
if(head == tail)
return NULL;
ListNode *fast = head;
ListNode *slow = head;
while(fast != tail && fast->next != tail){
slow = slow->next;
fast = fast->next->next;
}
TreeNode *root = new TreeNode(slow->val);
root->left = toBST(head, slow);
root->right = toBST(slow->next, tail);
return root;
}
};
系列教程持續發佈中,歡迎訂閱、關注、收藏、評論、點贊哦~~( ̄▽ ̄~)~
完的汪(∪。∪)。。。zzz