给定一个单链表的头节点 head ,其中的元素 按升序排序 ,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差不超过 1。
解题思路:
一开始看到这题确实是一筹莫展,看了评论区才有了大体的思路,主要就是快速找到中点。然后递归找到左右结点,处理好结点为 null 与只有一个结点的情况。
这里贴出代码,我觉得这个版本的代码比较优雅。
public TreeNode sortedListToBST(ListNode head) {
if (head == null) return null;
if (head.next == null) return new TreeNode(head.val);
ListNode fast = head, slow = head, pre = null;
while (fast != null && fast.next != null) {
fast = fast.next.next;
pre = slow;
slow = slow.next;
}
TreeNode root = new TreeNode(slow.val);
pre.next = null;
ListNode rightList = slow.next;
root.left = sortedListToBST(head);
root.right = sortedListToBST(rightList);
return root;
}