zoukankan      html  css  js  c++  java
  • 二叉树的镜像

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

     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:
    ");
    56     Createb(&root);//生成二叉树
    57     Preorder(root);//先序遍历二叉树
    58     Mirror(root);
    59     Preorder(root);//先序遍历二叉树
    60 }
  • 相关阅读:
    -for循环案例(下)
    for循环案例(上)
    for循环
    判断语句案例
    判断语句
    操作符优先级
    windows 下安装图片标注软件 labelling和出错解决
    tf-faster rcnn
    目标检测——Faster R-CNN 详解、Pytorch搭建、训练自己的数据集
    java idea 配置安装
  • 原文地址:https://www.cnblogs.com/wxdjss/p/5450901.html
Copyright © 2011-2022 走看看