题目:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
链接: http://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
6/7/2017
2ms, 9%
用快慢指针找到中点,递归做左右子树,注意左子树最后一个node的next应该设为null
注意的问题
1. 左子树最后一个node的next应该设为null,第17行
2. 当head == slow也就是左子树为空的时候,不要递归调用,而应该直接设成null,第18行
1 public class Solution { 2 public TreeNode sortedListToBST(ListNode head) { 3 if (head == null) { 4 return null; 5 } 6 ListNode fast, slow, prev = head; 7 fast = head; 8 slow = head; 9 10 while (fast != null && fast.next != null) { 11 prev = slow; 12 slow = slow.next; 13 fast = fast.next.next; 14 } 15 TreeNode node = new TreeNode(slow.val); 16 node.right = sortedListToBST(slow.next); 17 prev.next = null; 18 node.left = (head == slow)? null: sortedListToBST(head); 19 return node; 20 } 21 }
别人的答案
in-order traversal + DFS
http://www.cnblogs.com/yrbbest/p/4437320.html
更多讨论
https://discuss.leetcode.com/category/117/convert-sorted-list-to-binary-search-tree