首页 > 其他 > 详细

[LeetCode 109] Convert Sorted List to Binary Search Tree

时间:2015-03-26 09:11:40      阅读:241      评论:0      收藏:0      [点我收藏+]

题目链接:convert-sorted-list-to-binary-search-tree


/**
 * 
		Given a singly linked list where elements are sorted in ascending order, 
		convert it to a height balanced BST.
 *
 */
public class ConvertSortedListToBinarySearchTree {

	public class ListNode {
		int val;
		ListNode next;

		ListNode(int x) {
			val = x;
			next = null;
		}
	}

	public class TreeNode {
		int val;
		TreeNode left;
		TreeNode right;

		TreeNode(int x) {
			val = x;
		}
	}
	
//	32 / 32 test cases passed.
//	Status: Accepted
//	Runtime: 294 ms
//	Submitted: 1 minute ago
	
	//自底向上法
	ListNode listHead;
	public TreeNode sortedListToBST(ListNode head) {
		this.listHead = head;
		ListNode cur = head;
		int len = 0;
		while(cur != null) {
			len++;
			cur = cur.next;
		}
		return sortedListToBST(0, len - 1);
	}
	public TreeNode sortedListToBST(int left, int right) {
		if(left > right) {
			return null;
		}
		int mid = (left + right) / 2;
		TreeNode leftNode = sortedListToBST(left, mid - 1);
		
		TreeNode root = new TreeNode(listHead.val);
		root.left = leftNode;
		listHead = listHead.next;
		
		root.right = sortedListToBST(mid + 1, right);
		return root;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}


[LeetCode 109] Convert Sorted List to Binary Search Tree

原文:http://blog.csdn.net/ever223/article/details/44629635

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