例如:下面兩棵樹互為鏡像
思路:先序遍歷樹的每個結點,若遍歷到的結點有子節點,則交換它的兩個結點。
#include "stdafx.h"
#include <iostream>
using namespace std;
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode *m_pLeft;
BinaryTreeNode *m_pRight;
};
//構造樹的鏡像
void Mirror(BinaryTreeNode *pRoot)
{
if (pRoot != NULL)
{
BinaryTreeNode *pTemp = NULL;
if (pRoot->m_pLeft != NULL || pRoot->m_pRight != NULL)
{
pTemp = pRoot->m_pLeft;
pRoot->m_pLeft = pRoot->m_pRight;
pRoot->m_pRight = pTemp;
}
if (pRoot->m_pLeft != NULL)
{
Mirror(pRoot->m_pLeft);
}
if (pRoot->m_pRight != NULL)
{
Mirror(pRoot->m_pRight);
}
}
}
//以先序的方式構建二叉樹,輸入-1表示結點為空
void CreateBinaryTree(BinaryTreeNode *&pRoot)
{
int nNodeValue = 0;
cin >> nNodeValue;
if (-1 == nNodeValue)
{
return;
}
else
{
pRoot = new BinaryTreeNode();
pRoot->m_nValue = nNodeValue;
CreateBinaryTree(pRoot->m_pLeft);
CreateBinaryTree(pRoot->m_pRight);
}
}
void PrintInOrder(BinaryTreeNode *&pRoot)
{
if (pRoot != NULL)
{
PrintInOrder(pRoot->m_pLeft);
cout << pRoot->m_nValue << " ";
PrintInOrder(pRoot->m_pRight);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
BinaryTreeNode *pRoot = NULL;
CreateBinaryTree(pRoot);
PrintInOrder(pRoot);
cout << endl;
Mirror(pRoot);
PrintInOrder(pRoot);
cout << endl;
system("pause");
return 0;
}