给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法一
以链表的中点作为根节点,左右链表再这样进行递归,放回根节点的值作为左孩子和右孩子。
代码
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if(!head) return NULL;
TreeNode* root;
if(!head->next)
{
root = new TreeNode(head->val);
return root;
}
ListNode* slow = head, *fast = head, *prev = head;
while (fast != NULL && fast->next != NULL)
{
fast = fast->next->next;
prev = slow;
slow = slow->next;
}
prev->next = NULL;
root = new TreeNode(slow->val);
root->left = sortedListToBST(head);
root->right = sortedListToBST(slow->next);
return root;
}
};