/** * 题目: * 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. * 解题思路: * 利用快慢指针找到中间节点,作为根节点,然后左子树即为左边链表部分,右子树即为右边链表部分,递归进行即可。 */ public class SortedListToBST_109_1016 { public TreeNode SortedListToBST(ListNode head) { if (head == null) { return null; } return BST(head, null); } public TreeNode BST(ListNode head, ListNode tail) { if (head == tail) { return null; } //利用快慢指针找到中间节点,作为根节点 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 = BST(head, slow); root.right = BST(slow.next, tail); return root; }
}