1. 程式人生 > >二進制查找樹轉換為雙向鏈表

二進制查找樹轉換為雙向鏈表

creat while cpp val oid 指針 lin chan span

全然依照海濤哥劍指offer裏邊的遞歸思路來寫的。基本一樣。僅作學習驗證。努力鍛煉。努力學習!

題目:輸入一棵二元查找樹,將該二元查找樹轉換成一個排序的雙向鏈表。要求不能創建不論什麽新的結點,僅僅調整指針的指向。

  比方將二元查找樹
10
/ \
6 14
/ \ /  \

 4 8 12   16
轉換成雙向鏈表

4=6=8=10=12=14=16

code例如以下:

//Change a BSTree to a sorted double linklist
struct BSTreeNode 
{
	int value;
	BSTreeNode *left;
	BSTreeNode *right;
}head;
//Create a node of BSTree for test
BSTreeNode* CreateNode(int value)
{
	BSTreeNode *node = new BSTreeNode();
	node->value = value;
	node->left = NULL;
	node->right = NULL;
	return node;
}
//using a lastNode pointer to convert the pointer of the node
void ConvertNode(BSTreeNode *head, BSTreeNode **lastNode)
{
	if(head == NULL)
		return;
	BSTreeNode *pCurrent = head;
	if(pCurrent->left != NULL)
		ConvertNode(pCurrent->left, lastNode);
	pCurrent->left = *lastNode;
	if(*lastNode != NULL)
		(*lastNode)->right = pCurrent;
	*lastNode = pCurrent;
	if(pCurrent->right != NULL)
		ConvertNode(pCurrent->right, lastNode);
}
//lastNode pointer is pointing to the rear,so the head can be obtained 
BSTreeNode* Convert(BSTreeNode *head)
{
	if(head == NULL)
		return NULL;
	BSTreeNode *lastNode = NULL;
	ConvertNode(head, &lastNode);
	while(lastNode->left != NULL)
		lastNode = lastNode->left;
	return lastNode;
}
//main function for test
int main()
{
	BSTreeNode *head = CreateNode(10);
	head->left = CreateNode(8);
	head->left->left = CreateNode(7);
	head->left->right = CreateNode(9);
	head->right = CreateNode(12);
	head->right->left = CreateNode(11);
	head = Convert(head);
	while(head != NULL)
	{
		printf("%d ",head->value);
		head = head->right;
	}
}


二進制查找樹轉換為雙向鏈表