题目链接:convert-sorted-list-to-binary-search-tree
/** * Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. * */ public class ConvertSortedListToBinarySearchTree { public class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } } public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } // 32 / 32 test cases passed. // Status: Accepted // Runtime: 294 ms // Submitted: 1 minute ago //自底向上法 ListNode listHead; public TreeNode sortedListToBST(ListNode head) { this.listHead = head; ListNode cur = head; int len = 0; while(cur != null) { len++; cur = cur.next; } return sortedListToBST(0, len - 1); } public TreeNode sortedListToBST(int left, int right) { if(left > right) { return null; } int mid = (left + right) / 2; TreeNode leftNode = sortedListToBST(left, mid - 1); TreeNode root = new TreeNode(listHead.val); root.left = leftNode; listHead = listHead.next; root.right = sortedListToBST(mid + 1, right); return root; } public static void main(String[] args) { // TODO Auto-generated method stub } }
[LeetCode 109] Convert Sorted List to Binary Search Tree
原文:http://blog.csdn.net/ever223/article/details/44629635