题目
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
分析
递归不断构造左右子树
普通构造方法(解法1)就是每次递归调用都要去遍历找到中间的节点。
高端点的方法(解法2),类似中序遍历树的写法,先构造左子树,左子树构造完时,链表上的指针刚好指向中间节点,再构造右子树即可。
解法1
public TreeNode sortedListToBST(ListNode head) { if (head == null) { return null; } int n = 0; ListNode p = head; while (p != null) { ++n; p = p.next; } return solve(head, n - 1); } private TreeNode solve(ListNode head, int high) { if (high < 0) { return null; } int mid = high / 2; ListNode p = head; for (int i = 0; i < mid; ++i) { p = p.next; } TreeNode root = new TreeNode(p.val); root.left = solve(head, mid - 1); root.right = solve(p.next, high - mid - 1); return root; }
解法2
public class ConvertSortedListToBinarySearchTree { private ListNode head; public TreeNode sortedListToBST(ListNode head) { if (head == null) { return null; } this.head = head; int n = 0; ListNode p = head; while (p != null) { ++n; p = p.next; } return solve(0, n - 1); } private TreeNode solve(int low, int high) { if (low > high) { return null; } int mid = low + (high - low) / 2; TreeNode left = solve(low, mid - 1); TreeNode root = new TreeNode(head.val); head = head.next; TreeNode right = solve(mid + 1, high); root.left = left; root.right = right; return root; } }
LeetCode | Convert Sorted List to Binary Search Tree,布布扣,bubuko.com
LeetCode | Convert Sorted List to Binary Search Tree
原文:http://blog.csdn.net/perfect8886/article/details/20164925