二叉树的镜像原理很简单,就是左子树变成右子树,每个节点都遵循这个原则就是镜像,直接来看代码
//二叉树镜像(递归)
void _GetBinaryMirror(Node* _pRoot)
{
if (_pRoot == NULL)
return;
Node* pCur = _pRoot;
if (pCur->_pLeft == NULL && pCur->_pRight == NULL)
return;
swap(pCur->_pLeft, pCur->_pRight);
if (pCur->_pLeft != NULL)
_GetBinaryMirror(pCur->_pLeft);
if (pCur->_pRight != NULL)
_GetBinaryMirror(pCur->_pRight);
}
//镜像(非递归-->队列)
void _GetBinaryMirror_Nor(Node* _pRoot)
{
if (_pRoot == NULL)
return;
Node* pCur = _pRoot;
queue<Node*> q;
q.push(pCur);
while (!q.empty())
{
Node* front = q.front();
if (front->_pLeft != NULL || front->_pRight != NULL)
swap(front->_pLeft, front->_pRight);
if (front->_pLeft != NULL)
q.push(front->_pLeft);
if (front->_pRight != NULL)
q.push(front->_pRight);
q.pop();
}
}