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

leetcode__Convert Sorted List to Binary Search Tree

时间:2014-06-21 23:57:00      阅读:351      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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





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

leetcode__Convert Sorted List to Binary Search Tree

标签:leetcode

原文地址:http://blog.csdn.net/xuerenlv123/article/details/32123219

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