设为首页 加入收藏

TOP

二叉树镜像
2014-11-23 22:00:02 来源: 作者: 【 】 浏览:26
Tags:

题目描述:


输入一个二叉树,输出其镜像。


二叉树镜像


九度OJ的测试很蛋疼啊~ 这里,我先写一个求二叉树镜像的代码,使用自己的测试代码: 思路很简单:先判断是否左右孩子都为空,如果不是,则交换,然后递归左右子树。其实是先序遍历。


/*
二叉树镜像
by Rowandjj
2014/8/1
*/
#include
using namespace std;
typedef struct _BNODE_
{
int data;
struct _BNODE_ *lChild;
struct _BNODE_ *rChild;
}BNode,*pTree;
//求二叉树镜像,先序遍历的方式
//先判断是否左右孩子都为空,如果不是,则交换,然后递归左右子树
void getMirror(pTree pT)
{
if(pT == NULL)
{
return;
}
if(pT->lChild==NULL && pT->rChild==NULL)
{
return;
}
//交换
BNode *temp = pT->lChild;
pT->lChild = pT->rChild;
pT->rChild = temp;
//递归
if(pT->lChild)
{
getMirror(pT->lChild);
}
if(pT->rChild)
{
getMirror(pT->rChild);
}
}
void Create(pTree *ppTree)
{
int data;
cin>>data;

if(data != -1)
{
*ppTree = (BNode*)malloc(sizeof(BNode));
if(*ppTree == NULL)
{
exit(-1);
}
(*ppTree)->data = data;
(*ppTree)->lChild = NULL;
(*ppTree)->rChild = NULL;
Create(&(*ppTree)->lChild);
Create(&(*ppTree)->rChild);
}
}
//先序遍历
void PreTraverse(pTree pT)
{
if(!pT)
{
return;
}
cout<data<<" ";
if(pT->lChild)
PreTraverse(pT->lChild);
if(pT->rChild)
PreTraverse(pT->rChild);
}
int main()
{
pTree pT = NULL;
Create(&pT);
PreTraverse(pT);
cout<<"\n---------------------\n";
getMirror(pT);
PreTraverse(pT);
return 0;
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Android ImageView 图片等比缩放.. 下一篇从上到下遍历二叉树

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: