二叉搜索树要求我们根节点的左子树一定小于根节点的值,右子树一定大于跟节点的值。而平衡二叉树要求我们左右两边子树的高度差不超过1。
又由于给出的链表已经是排好序的了,所以此时我们只需要寻找到链表的中点,以链表中点为界限,中点左边是二叉搜索树的左孩子们,中点的右边是二叉树的右孩子们,进行递归地构造。这题就解决了。
TreeNode* sortedListToBST(ListNode* head)
{
if(head==nullptr) return nullptr;
return sortedListToBST(head,nullptr);
}
TreeNode* sortedListToBST(ListNode* head, ListNode* tail)
{
if(head==tail) return nullptr;
ListNode* slow=head;
ListNode* fast=head;
//寻找链表中点,以中点为界构造二叉树
while(fast!=tail && fast->next!=tail)
{
fast=fast->next->next;
slow=slow->next;
}
TreeNode* root=new TreeNode(slow->val);
root->left=sortedListToBST(head,slow);
root->right=sortedListToBST(slow->next,tail);
return root;
}