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

Convert Sorted List to Binary Search Tree

时间:2014-06-20 09:46:33      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:leetcode   链表      java   

题目

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

标签:leetcode   链表      java   

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

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