您的位置:首页 > 其它

算法-二叉树转双向链表

2013-10-14 10:55 330 查看
原文链接:点击打开链接

不申请新节点 将二叉树转换成双向链表

总结一下:在中序遍历中 进行转换

原题:

输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。

之后就是定义三个功能函数了:

1.创建二元查找树的addBSTreeNode(BSTreeNode * & pCurrent,int value);

2.遍历二元查找树的void
ergodicBSTree(BSTreeNode * pCurrent);



3.
二叉树转换成list的
convertToDoubleList(BSTreeNode * pCurrent);


3.源码:


借用结构之法算法之道博主July写的源码



struct BSTreeNode {
	int m_nValue;
	BSTreeNode* m_pLeft;
	BSTreeNode* m_pRight;
};

typedef BSTreeNode DoubleList;
DoubleList * pHead;
DoubleList * pListIndex;

void convertToDoubleList(BSTreeNode* pCurrent);

//创建二叉查找树
void addBSTreeNode(BSTreeNode * &pCurrent, int value) 
//传的是pRoot的地址,所以对pCurrent的操作就是对pRoot的操作
{
	if (pCurrent == NULL)
	{
		BSTreeNode* pBSTree = new BSTreeNode();
		pBSTree->m_pLeft = NULL;
		pBSTree->m_pRight = NULL;
		pBSTree->m_nValue = value;
		pCurrent = pBSTree;
	}
	else
	{
		if ((pCurrent->m_nValue) > value)
		{
			addBSTreeNode(pCurrent->m_pLeft, value);
		}
		else if((pCurrent->m_nValue) < value)
		{
			addBSTreeNode(pCurrent->m_pRight, value);
		}
		else
			cout<<"重复加入节点"<<endl;
	}
}

void ergodicBSTree(BSTreeNode* pCurrent)
{
	if (pCurrent == NULL)
	{
		return;
	}

	if (pCurrent->m_pLeft != NULL)
	{
		ergodicBSTree(pCurrent->m_pLeft);
	}

	convertToDoubleList(pCurrent);

	if (pCurrent->m_pRight != NULL)
	{
		ergodicBSTree(pCurrent->m_pRight);
	}
}

void convertToDoubleList(BSTreeNode* pCurrent)
{
	pCurrent->m_pLeft = pListIndex;
	if (pListIndex != NULL)
	{
		pListIndex->m_pRight = pCurrent;
	}
	else
	{
		pHead = pCurrent;
	}
	pListIndex = pCurrent;
	cout<<pCurrent->m_nValue<<endl;
}


ps:写的不错,July在算法上有非常深的功底,他的博文主页:http://my.csdn.net/v_july_v
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: