题目:
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.
解答:
根据有个有序链表,确定一个平衡二叉搜索树
解题思路为:
- 因为要求二叉搜索树平衡,且链表本身有序,所以想到找到链表的中间值作为根节点,该中间值的左侧为根节点的左子树,右节点为根节点的右子树,以此递归实现。
- 其中,寻找链表的中间值,可以采用快慢指针的方法,在之前的题目中也有多次用到。
代码实现如下:
class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head == null) {
return null;
}
return toBST(head, null);
}
private TreeNode toBST(ListNode start, ListNode end) {
if(start == end) {
return null;
}
ListNode slow = start;
ListNode fast = start;
while(fast != end && fast.next != end) {
slow = slow.next;
fast = fast.next.next;
}
TreeNode node = new TreeNode(slow.val);
node.left = toBST(start, slow);
node.right = toBST(slow.next, end);
return node;
}
}