您的位置:首页 > 其它

二叉树的镜像变换

2013-10-28 19:11 447 查看


#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;
}




1 //二叉树的镜像变换
#include <iostream>
#include <stack>
using namespace std;

//二叉树结构
struct BTreeNode
{
int m_nValue;
BTreeNode *m_pLeft;
BTreeNode *m_pRight;
};

//递归实现
void MirrorRecursively(BTreeNode *pNode)
{
if(!pNode)
{
return;
}
//交换左右孩子
BTreeNode *pTemp = pNode->m_pLeft;
pNode->m_pLeft = pNode->m_pRight;
pNode->m_pRight = pTemp;

if(pNode->m_pLeft)
{
MirrorRecursively(pNode->m_pLeft);
}

if(pNode->m_pRight)
{
MirrorRecursively(pNode->m_pRight);
}
}

void MirrorIteratively(BTreeNode *pNode)
{
if(!pNode)
{
return ;
}

stack<BTreeNode *> stackTreeNode;
stackTreeNode.push(pNode);

while(stackTreeNode.size())
{
BTreeNode *pNode = stackTreeNode.top();
stackTreeNode.pop();

//交换左右孩子
BTreeNode *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);
}
}

}

//按照先序创建二叉树,0表示空
BTreeNode *Create()
{
int ch;
cin>> ch;
if(ch == 0)
{
return NULL;
}
else
{
BTreeNode *root = new BTreeNode();
root->m_nValue = ch;
root->m_pLeft = Create();
root->m_pRight = Create();
return root;
}
}

//按照先序 打印 树
void printBTree(BTreeNode *root)
{
if(!root)
{
return ;
}
cout << root->m_nValue <<" ";
printBTree(root->m_pLeft);
printBTree(root->m_pRight);
}

void main()
{
BTreeNode *tree = NULL;
cout << "先序创建二叉树:";
tree = Create();
cout << "先序打印二叉树:";
printBTree(tree);

MirrorRecursively(tree);
cout <<endl<<"变换后:";
printBTree(tree);

cout <<endl<<"再次变换:";
MirrorIteratively(tree);
printBTree(tree);
cout << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: