Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
和有序数组的思想基本一样,将链表进行二分。TreeNode getBST(ListNode head, int len) { if (head == null || len == 0) { return null; } int median = len / 2; ListNode node = head; for (int i = 0; i < median; i++) { node = node.next; } TreeNode root = new TreeNode(node.val); root.left = getBST(head, median); root.right = getBST(node.next, len - median - 1); return root; } public TreeNode sortedListToBST(ListNode head) { int len = 0; ListNode node = head; while(node != null) { node = node.next; len++; } return getBST(head, len); }
Convert Sorted List to Binary Search Tree,布布扣,bubuko.com
Convert Sorted List to Binary Search Tree
原文地址:http://blog.csdn.net/u010378705/article/details/28594333