Leetcode 109. Convert Sorted List to Binary Search Tree

我的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);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值