leetcode:(109)Conver Sorted List To BST(java)
阿新 • • 發佈:2018-11-06
/** * 題目: * 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; }
}