Convert Sorted List to Binary Search Tree

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
想了好久想不出来。后来看了题目分类里面说是DFS,可是没有想出DFS的算法来。后来想到了一个递归的方法。可是空间和时间都是O(n)。
后来网上找了一个空间是O(1)的时间是O(n)的算法,是一种新的解题思路,用的是中递归。

一般我解题都是用的头递归或者尾递归。第一次见识到了中递归,相当于把递归当成了一个循环体,用引用来作为变量,每一个递归中改动,须要非常强大的想象力。把整个递归树在脑子里想清楚。

空间和时间都为O(n):

    TreeNode *sortedListToBST(ListNode *head) 
	{
		vector<TreeNode*> treeNodes;
		while (head != NULL)
		{
			TreeNode *node = new TreeNode(head->val);
			treeNodes.push_back(node);
			head = head->next;
		}
		return genBST(0, treeNodes.size()-1, treeNodes);
    }
	
	TreeNode* genBST(int start, int end, vector<TreeNode*> &treeNodes)
	{
		if (start == end) return treeNodes[start];
		else if (start+1 == end)
		{
			treeNodes[start]->right = treeNodes[end];
			return treeNodes[start];
		} 

		int mid = (start+end)/2;
		TreeNode* root = treeNodes[mid];
		root->left = genBST(start, mid-1, treeNodes);
		root->right = genBST(mid+1, end, treeNodes);
		return root;
	}

空间为O(1)时间为O(n):

	TreeNode *sortedListToBST(ListNode *head)
	{
	    int len = 0;
        ListNode * node = head;
        while (node != NULL)
        {
            node = node->next;
            len++;
        }
        return buildTree(head, 0, len-1);
    }
    
    TreeNode *buildTree(ListNode *&node, int start, int end)
    {
        if (start > end) return NULL;
        int mid = start + (end - start)/2;
        TreeNode *left = buildTree(node, start, mid-1);
        TreeNode *root = new TreeNode(node->val);
        root->left = left;
        node = node->next;
        root->right = buildTree(node, mid+1, end);
        return root;
    }
解法引用:http://www.bwscitech.com/a/jishuzixun/javayuyan/2013/0930/15822.html

以上是关于Convert Sorted List to Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章

109.Convert sorted list to BST

Convert Sorted List to Binary Search Tree

Convert Sorted List to Balanced BST

109. Convert Sorted List to Binary Search Tree

Convert Sorted List to Binary Search Tree

convert-sorted-list-to-binary-search-tree