标签:style blog http color strong os
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
主要问题是链表中间节点不易获得。
思路1:链表转化成数组,然后上题做法。需要额外O(N)空间。
思路2:每次都从头找到中间节点,时间复杂度为O(NlogN)。
思路3:换一个思路,这次不top-down,而是bottom-up来做。一遍遍历链表,一遍中序遍历的顺序构建二叉树。
public class Solution { public TreeNode sortedListToBST(ListNode head) { int len = 0; ListNode p = head; while (p != null) { len++; p = p.next; } ListNode[] wrap = new ListNode[1]; wrap[0] = head; return SLtoBST(wrap, 0, len); } private TreeNode SLtoBST(ListNode[] wrap, int start, int end) { if (start >= end) return null; int mid = start + (end - start) / 2; TreeNode left = SLtoBST(wrap, start, mid); TreeNode root = new TreeNode(wrap[0].val); root.left = left; wrap[0] = wrap[0].next; root.right = SLtoBST(wrap, mid + 1, end); return root; } public static void main(String[] args) { ListNode head = ListUtils.makeList(1); TreeNode root = new Solution().sortedListToBST(head); } }
参考:
http://www.cnblogs.com/feiling/p/3267917.html
[leetcode] Convert Sorted List to Binary Search Tree,布布扣,bubuko.com
[leetcode] Convert Sorted List to Binary Search Tree
标签:style blog http color strong os
原文地址:http://www.cnblogs.com/jdflyfly/p/3821408.html