数据结构-二叉树的镜像

题目:请完成一个函数,输入一个二叉树,该函数输出他的镜像

分析:利用图形画出二叉树的镜像进行分析。

树是数据结构的重中之重,尤其是树的实现大部分是用递归。好好花点时间琢磨一下,硬伤这是。

/*
剑指offer面试题19
*/
#include <iostream>

using namespace std;

struct BinaryTree{
    BinaryTree* lchild;
    BinaryTree* rchild;
    int data;
};

BinaryTree* Create(){
    BinaryTree* root = new BinaryTree;
    root->data = 8;
    BinaryTree* lchild = new BinaryTree;
    lchild->data = 6;
    BinaryTree* rchild = new BinaryTree;
    rchild->data = 7;
    root->lchild = lchild;
    root->rchild = rchild;

    BinaryTree* lchild1 = new BinaryTree;
    lchild1->data = 9;
    BinaryTree* rchild1 = new BinaryTree;
    rchild1->data = 2;
    lchild->lchild = lchild1;
    lchild->rchild = rchild1;

    BinaryTree* lchild2 = new BinaryTree;
    lchild2->data = 4;
    BinaryTree* rchild2 = new BinaryTree;
    rchild2->data = 5;
    rchild1->lchild = lchild2;
    rchild1->rchild = rchild2;
    return root;
}

void MirrorTree(BinaryTree* root){
    if(root == NULL || (root->lchild == NULL && root->rchild == NULL)){
        return;
    }

    BinaryTree* mTree = root->lchild;
    root->lchild = root->rchild;
    root->rchild = mTree;

    if(root->lchild){
        MirrorTree(root->lchild);
    }
    if(root->rchild){
        MirrorTree(root->rchild);
    }
}

void print(BinaryTree* root){
    if(root != NULL){
        cout << root->data << " ";
        print(root->lchild);
        print(root->rchild);
    }
}

int main()
{
    BinaryTree* bTree = Create();

    MirrorTree(bTree);

    print(bTree);

    return 0;
}

 

转载于:https://www.cnblogs.com/wn19910213/p/3728670.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值