题目:
将一个二叉树转换为一个双向链表。要求不能创建新的节点,只能调整节点的指针。
思路:
code:
node* Convert(node* pRoot)
{
node* pLastNode = NULL;
ConvertNode(pRoot , pLastNode);
node* pHead = pLastNode;
while (pHead && pHead->pLeft ) //从当前位置找到头结点
{
pHead = pHead->pLeft;
}
return pHead;
}
void ConvertNode(node* pNode ,node*& pLastNode)
{
if (pNode == NULL)
return;
node* pCur = pNode;
//树的最左节点作为链表的头
if (pCur->pLeft)
ConvertNode(pCur->pLeft, pLastNode);
pCur->pLeft = pLastNode; //前指针
if (pLastNode)
pLastNode->pRight = pCur;
pLastNode = pCur; //后指针
if (pCur->pRight)
ConvertNode(pCur->pRight, pLastNode);
}