首页 > 编程语言 > 详细

Java for LeetCode 109 Convert Sorted List to Binary Search Tree

时间:2015-05-23 21:11:11      阅读:205      评论:0      收藏:0      [点我收藏+]

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

解题思路:

同上题,JAVA实现如下:

    public TreeNode sortedListToBST(ListNode head) {
        ArrayList<Integer> list=new ArrayList<Integer>();
        while(head!=null){
        	list.add(head.val);
        	head=head.next;
        }
        return sortedListToBST(list,0,list.size()-1);
    }
	static public TreeNode sortedListToBST(ArrayList<Integer> list, int begin, int end) {
		if (begin>end)
			return null;
		TreeNode root = new TreeNode(list.get((begin+end) / 2));
		root.left=sortedListToBST(list,begin,(begin+end) / 2-1);
		root.right=sortedListToBST(list,(begin+end) / 2+1,end);
		return root;
	}

 

Java for LeetCode 109 Convert Sorted List to Binary Search Tree

原文:http://www.cnblogs.com/tonyluis/p/4524797.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!