我的leetcode代码已经放入github:https://github.com/gaohongbin/leetcode
题目:将一个升序的单向链表,转换成平衡的二叉搜索树。
旧思路:就像108题一样,我们一般做的是把数组转成二叉树,但是一个单向链表,我刚开始的思路是也像数组一样,就是每次找a[i]的时候,都要从表头开始找到第i个节点,但是这种思路显然很笨。
新思路:这个是在网上看的别人的代码,虽然关键的代码只有七行,但是已经被原作者那强大的思维能力深深震撼了,虽然也是用的递归,但是递归我从来没这么用过。
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Leetcode109 {
static ListNode h;
public static TreeNode sortedListToBST(ListNode head) {
if(head==null)
return null;
int size = 0;
h = head;
ListNode p = head;
while(p!=null){
size++;
p=p.next;
}
return sortedListToBSThelper(0,size-1);
}
public static TreeNode sortedListToBSThelper(int start, int end){
if(start > end)
return null;
int mid = (end + start)/2;
TreeNode left = sortedListToBSThelper(start,mid-1);
TreeNode root = new TreeNode(h.val); //这里的h已经不是表头了,因为在上一句处理left的时候,h作为全局变量,已经发生变化。
root.left = left;
h = h.next;
TreeNode right = sortedListToBSThelper(mid+1,end);
root.right = right;
return root;
}
public static void main(String[] args){
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = null;
TreeNode root = sortedListToBST(head);
System.out.println(root.val);
System.out.println(root.left.val);
System.out.println(root.right.val);
}
}