输入一颗二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的节点,只能调整树种节点指针的指向。
节点定义如下:
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
思路:二叉搜索树的中序遍历是刚好排序的!!!!!
BinaryTreeNode* Convert(BinaryTreeNode* pRootOfTree)
{
BinaryTreeNode *pLastNodeInList=nullptr;
ConvertNode(pRootOfTree,&pLastNodeInList);
BinaryTreeNode *pHeadOfList=pLastNodeInList;
while(pHeadOfList!=nullptr&&pHeadOfList->m_pLeft!=nullptr)
pHeadOfList=pHeadOfList->m_pLeft;
return pHeadOfList;
}
void ConvertNode(BinaryTreeNode* pNode,BinaryTreeNode** pLastNodeInList)
{
if(pNode==nullptr)
return;
BinaryTreeNode *pCurrent=pNode;
if(pCurrent->m_pLeft!=nullptr)
ConvertNode(pCurrent->m_pLeft,pLastNodeInList);
pCurrent->m_pLeft=*pLastNodeInList;
if(*pLastNodeInList!=nullptr)
(*pLastNodeInList)->m_pRight=pCurrent;
*pLastNodeInList=pCurrent;
if(pCurrent->m_pRight!=nullptr)
ConvertNode(pCurrent->m_pRight,pLastNodeInList);
}