题目描述:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
题目解析:
通过快慢指针找到链表的中点,作为二叉搜素树的根节点。以中点为界,将链表分为两部分,不包含中点,分别对两部分链表递归调用原函数,最后连上根节点的左右子树。
AC代码:
/**
* 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* slow = head;
ListNode* fast = 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;
}
};
(*^▽^*)