码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的镜像

时间:2016-05-01 19:15:54      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

请完成一个函数,输入一个二叉树,该函数输出它的镜像。

技术分享

 1 #include<iostream>
 2 using namespace std;
 3 
 4 typedef struct node
 5 {
 6 char data;//结点数据
 7 struct node *lchild,*rchild;//二叉树结点类型
 8 }BSTree;//二叉树结点类型
 9 
10 
11 void Createb(BSTree **p)//建立二叉树
12 {
13     char ch;
14     cin>>ch;
15     if(ch!=.)
16     {
17         *p=(BSTree*)malloc(sizeof(BSTree));//申请空间
18         (*p)->data=ch;//空间赋值
19         Createb(&(*p)->lchild);//生成左子树
20         Createb(&(*p)->rchild);//生成右子树
21     }
22     else *p=NULL;//空结点
23 }
24 
25 void Preorder(BSTree *p)//先序遍历二叉树
26 {
27     if(p!=NULL)
28     {
29         printf("%3c",p->data);
30         Preorder(p->lchild);
31         Preorder(p->rchild);
32     }
33 }
34 
35 void Mirror(BSTree *root)
36 {
37  if(root==NULL)
38      return;
39  if(root->rchild==NULL&&root->lchild==NULL)
40      return;
41  BSTree *temp=root->lchild;
42  root->lchild=root->rchild;
43  root->rchild=temp;
44  if(root->lchild)
45      Mirror(root->lchild);
46  if(root->rchild)
47      Mirror(root->rchild);
48 }
49 
50 
51 
52 void main()
53 {
54     BSTree *root;
55     printf("create BSTree root:\n");
56     Createb(&root);//生成二叉树
57     Preorder(root);//先序遍历二叉树
58     Mirror(root);
59     Preorder(root);//先序遍历二叉树
60 }

 

二叉树的镜像

标签:

原文地址:http://www.cnblogs.com/wxdjss/p/5450901.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!