首页 > 其他 > 详细

Convert Sorted List to Binary Search Tree

时间:2014-06-20 09:40:21      阅读:352      评论:0      收藏:0      [点我收藏+]

题目

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

方法

和有序数组的思想基本一样,将链表进行二分。
	TreeNode getBST(ListNode head, int len) {
		if (head == null || len == 0) {
			return null;
		}
		
		int median = len / 2;
		ListNode node = head;
		for (int i = 0; i < median; i++) {
			node = node.next;
		}
		TreeNode root = new TreeNode(node.val);
		root.left = getBST(head, median);
		root.right = getBST(node.next, len - median - 1);
		return root;
	}
    public TreeNode sortedListToBST(ListNode head) {
    	int len = 0;
    	ListNode node = head;
    	while(node != null) {
    		node = node.next;
    		len++;
    	}
    	return getBST(head, len);      
    }


Convert Sorted List to Binary Search Tree,布布扣,bubuko.com

Convert Sorted List to Binary Search Tree

原文:http://blog.csdn.net/u010378705/article/details/28594333

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