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

leetcode__Convert Sorted List to Binary Search Tree

Convert Sorted List to Binary Search Tree

 Total Accepted: 12283 Total Submissions: 45910My Submissions

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




总结:这个是网上找的,还不明确为什么是以下这个样子,去掉&,就出错

ListNode *&node


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;
    }



总结:这个開始的时候有点问题,改动了一下

TreeNode *sortedListToBST(ListNode *head) 
	{
		vector<TreeNode*> treeNodes;
		if(head == NULL) return NULL;
		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;
	}



总结:上面这个代码跟我參考得到的思想一致,可是我的是time limit

TreeNode *sortedListToBST(ListNode *head) {
		int len = 0;
		ListNode *node = head;
		while(node)
		{
			len++;
			node = node->next;
		}
        return BuildTree(head,1,len);
}

	TreeNode *BuildTree(ListNode *node,int start,int end)
	{
		if(start > end) return NULL;
		int mid = start + (end-start)/2;	
		ListNode *mi_node = node;
		for(int i=1;i<mid;i++)
		{
			mi_node = mi_node->next;
		}

		TreeNode *root = new TreeNode(mi_node->val); 
		root->left = BuildTree(node,start,mid-1);
		root->right = BuildTree(node,mid+1,end);
		return root;
	}