数据结构-二叉树的镜像

原文链接:http://www.cnblogs.com/wn19910213/p/3728670.html

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

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

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

/*
剑指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

上一篇:【数据结构】树


下一篇:关于层次遍历二叉树的一些算法总结