/*****************递归交换左右子女*******************/
void exchangeChild(BiTreeNode* &T)
{
if(T==NULL)return;
BiTreeNode *temp = NULL;
cout << T->data << " ";
if(T->lchild||T->rchild)
{
temp = T->lchild;
T->lchild = T->rchild;
T->rchild = temp;
exchangeChild(T->lchild);
exchangeChild(T->rchild);
}
return;
}
http://zhuyanfeng.com/archives/3170
循环
由于递归的本质是编译器生成了一个函数调用的栈,因此用循环来完成同样任务时,最简单的办法就是用一个辅助栈来模拟递归。首先把树的头结点放入栈中。在循环中,只要栈不为空,弹出栈的栈顶结点,交换它的左右子树。如果它有左子树,把它的左子树压入栈中;如果它有右子树,把它的右子树压入栈中。这样在下次循环中就能交换它儿子结点的左右子树了。
参考代码如下:
void MirrorIteratively(BinaryTreeNode* pRoot)
{
if (pRoot == NULL)
return;
std::stack<BinaryTreeNode*> stackTreeNode;
stackTreeNode.push(pRoot);
while (stackTreeNode.size() > 0)
{
BinaryTreeNode *pNode = stackTreeNode.top();
stackTreeNode.pop();
BinaryTreeNode *pTemp = pNode->m_pLeft;
pNode->m_pLeft = pNode->m_pRight;
pNode->m_pRight = pTemp;
if (pNode->m_pLeft)
stackTreeNode.push(pNode->m_pLeft);
if (pNode->m_pRight)
stackTreeNode.push(pNode->m_pRight);
}
}
整理自《剑指Offer》