面试题27:输入一颗二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。
void convertNode(BinaryTreeNode* pNode,BinaryTreeNode** pLastNodeInList){
if(pNode==NULL)
return;
BinaryTreeNode* pCurrent=pNode;
if(pNode->m_pLeft)
convertNode(pNode->m_pLeft,pLastNodeInList);
pCurrent->m_pLeft=*pLastNodeInList;
if(*pLastNodeInList!=NULL)
(*pLastNodeInList)->m_pRight=pCurrent;
*pLastNodeInList=pCurrent;
if(pNode->m_pRight)
convertNode(pNode->m_pRight,pLastNodeInList);
}
BinaryTreeNode* convert(BinaryTreeNode* pRoot){
BinaryTreeNode* pLastNodeInList=NULL;
convertNode(pRoot,&pLastNodeInList);
BinaryTreeNode* pHeadofList=pLastNodeInList;
while(pHeadofList!=NULL&&pHeadofList->m_pLeft!=NULL)
pHeadofList = pHeadofList->m_pLeft;
return pHeadofList;
}
参考:《剑指offer》何海涛著