首页 > 代码库 > Convert Sorted List to Binary Search Tree

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.

方法

和有序数组的思想基本一样,将链表进行二分。
	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);      
    }