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

Convert Sorted List to Binary Search Tree--LeetCode

时间:2015-04-04 12:17:29      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   算法   

题目:

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

思路:和上面的思想一样,只不过注意找到链表的中间节点的方法

void Inorder(BinTree* root)
{
     if(root == NULL)
       return ;
     Inorder(root->left);
     cout<<root->value<<endl;
     Inorder(root->right);
     }


List* FindMid(List*& list,List*& head,List* tail)
{
	List* fast = head;
	List* slow = head;
	while(fast != NULL && fast->next != tail)
	{
		slow = slow->next;
		fast = fast->next;
		if(fast != NULL && fast->next != tail)
			fast=fast->next;
	}
	return slow;
}

BinTree* helper(List*& root,List*& head,List*& tail)
{
	BinTree* node = NULL;
	if(head == tail || head == NULL)
		return node;
	List* mid = FindMid(root,head,tail);
	List* next = mid->next;
	node = new BinTree;
	node->value = mid->value;
	node->left = node->right = NULL;
	node->left = helper(root,head,mid);
	node->right = helper(root,next,tail);
	return node;
}

BinTree* ConvertBST(List*& list)
{
	BinTree* root = NULL;
	if(list ==NULL)
		return root;
	List* head=list;
	List* tail=NULL;
	root = helper(list,head,tail);
	return root;
}

int main() 
{
	int array[]={1,2,3,4,5,6,7,8,9,10};
	//int array[]={1,4,3,2,5,2};
	List* list;
	Init_List(list,array,sizeof(array)/sizeof(int));
	BinTree* root = ConvertBST(list);
	 
		Inorder(root);
	return 0;
}


Convert Sorted List to Binary Search Tree--LeetCode

标签:c++   leetcode   算法   

原文地址:http://blog.csdn.net/yusiguyuan/article/details/44871893

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