题目描述
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.
Example1:
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 == nullptr){
return nullptr;
}
return convertBST(head, nullptr);
}
TreeNode* convertBST(ListNode* head, ListNode* tail){
if(head == tail){
return nullptr;
}
ListNode* slow = head;
ListNode* fast = head;
while(fast != tail && fast -> next != tail){ // 这里需要注意,不应该为nullptr,而是不等于tail,分为左右两边
fast = fast -> next -> next;
slow = slow -> next;
}
TreeNode* root = new TreeNode(slow -> val);
root -> left = convertBST(head, slow);
root -> right = convertBST(slow -> next, tail);
return root;
}
};