码迷,mamicode.com
首页 > 其他好文 > 详细

Convert Sorted List to Binary Search Tree

时间:2014-12-16 21:05:05      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:weight bst   leetcode   

原题是这个样子:


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

Thoughts

If you are given an array, the problem is quite straightforward. But things get a little more complicated when you have a singly linked list instead of an array. Now you no longer have random access to an element in O(1) time. Therefore, you need to create nodes bottom-up, and assign them to its parents. The bottom-up approach enables us to access the list in its order at the same time as creating nodes.

参考:http://www.programcreek.com/2013/01/leetcode-convert-sorted-list-to-binary-search-tree-java/


代码如下:

	public TreeNode sortedListToBST(ListNode head) {
		if (head == null)
			return null;
		int len = 0;
		ListNode nextNode = head;
		while (nextNode != null) {
			nextNode = nextNode.next;
			len++;
		}

		return buildTree(head, 0, len - 1);

	}

	public TreeNode buildTree(ListNode head, int start, int end) {
		if (start > end)
			return null;
		int mid = (start + end) / 2;
		ListNode p = head;
		for (int i = start; i < mid; i++) {
			p = p.next;
		}

		TreeNode left = buildTree(head, start, mid - 1);
		TreeNode right = buildTree(p.next, mid + 1, end);

		TreeNode root = new TreeNode(p.val);

		root.left = left;
		root.right = right;
		
		return root;
	}


Convert Sorted List to Binary Search Tree

标签:weight bst   leetcode   

原文地址:http://blog.csdn.net/ivyvae/article/details/41964707

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!