先序遍历树的每个结点,若遍历到的结点有子结点,则交换它的两个子结点。
1. 递归求解:
voidMirroRecursively(BinaryTreeNode *pNode)
{
if(NULL == pNode)
return;
if(NULL == pNode->Left && NULL== pNode->Right)
return;
BinaryTreeNode *pTemp =pNode->Left;
pNode->Left = pNode->Right;
pNode->Right = pTemp;
if(pNode->Left)
MirroRecursively(pNode->Left);
if(pNode->Right)
MirroRecursively(pNode->Right);
}
2. 非递归求解(借助栈)
借助于栈,先交换两棵子树,再求完一棵子树的镜像后在求另一棵子树的镜像(纵向,深度优先)
voidMirrorNonRecurively(BinaryTreeNode *pNode)
{
if(NULL == pNode)
return;
stack<BinaryTreeNode *>stackTreeNode;
stackTreeNode.push(pNode);
while(stackTreeNode.size())
{
BinaryTreeNode *pNode =stackTreeNode.top();
stackTreeNode.pop();
if(NULL != pNode->Left || NULL !=pNode->Right)
{ //交换
BinaryTreeNode *pTemp =pNode->Left;
pNode->Left =pNode->Right;
pNode->Right = pTemp;
}
if(NULL != pNode->Left)
stackTreeNode.push(pNode->Left);
if(NULL != pNode->Right)
stackTreeNode.push(pNode->Right);
}
}
3. 非递归求解(借助队列)
借助于队列以用广度优先的顺序遍历一遍实现逐层镜像(横向,广度优先)
voidMirrorNonRecurively (BinaryTreeNode * root)
{
queue< BinaryTreeNode *> q;
q.push(root);
while(!q.empty())
{
BinaryTreeNode * r = q.front();
q.pop();
if(r->pLeft != NULL)
q.push(r->pLeft);
if(r->pRight != NULL)
q.push(r->pRight);
////交换
BinaryTreeNode * temp =r->pLeft;
r->pLeft = r->pRight;
r->pRight = temp;
}
}