递归方法非常简单:
1 void MirrorRecursively(BinaryTreeNode *pNode) 2 { 3 if((pNode == NULL) || (pNode->m_pLeft == NULL && pNode->m_pRight)) 4 return; 5 6 BinaryTreeNode *pTemp = pNode->m_pLeft; 7 pNode->m_pLeft = pNode->m_pRight; 8 pNode->m_pRight = pTemp; 9 10 if(pNode->m_pLeft)11 MirrorRecursively(pNode->m_pLeft); 12 13 if(pNode->m_pRight)14 MirrorRecursively(pNode->m_pRight); 15 }
循环需要利用stack:
1 void MirrorIteratively(BinaryTreeNode* pRoot) 2 { 3 if(pRoot == NULL) 4 return; 5 6 std::stackstackTreeNode; 7 stackTreeNode.push(pRoot); 8 9 while(stackTreeNode.size() > 0)10 {11 BinaryTreeNode *pNode = stackTreeNode.top();12 stackTreeNode.pop();13 14 BinaryTreeNode *pTemp = pNode->m_pLeft;15 pNode->m_pLeft = pNode->m_pRight;16 pNode->m_pRight = pTemp;17 18 if(pNode->m_pLeft)19 stackTreeNode.push(pNode->m_pLeft);20 21 if(pNode->m_pRight)22 stackTreeNode.push(pNode->m_pRight);23 }24 }