• 数据结构-二叉树的镜像


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

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

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

    /*
    剑指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;
    }
  • 相关阅读:
    WebUpLoder 能自动预览,能多实例,包括后台demo
    ajax请求总是进入Error里
    c#_1:后台post请求
    Echarts_1:水平柱体
    Hello World!
    python正则表达式
    python web.py出现ValueError: need more than 1 value to unpack
    web.py端口被占用的错误
    github commit时出现 Please tell me who you are.以及项目名称管理
    打飞机小游戏 python+pygame
  • 原文地址:https://www.cnblogs.com/wn19910213/p/3728670.html
Copyright © 2020-2023  润新知