(1)求二叉排序树的镜像(2)类的指针和引用的操作

  1. 给定一个二叉排序树,求取他的镜像,如下图所示:

  2. 在这里插入图片描述

  3. 二叉树的处理一般会用到递归。我们从根节点开始处理,先交换根节点的左右孩子,再对根节点的左右孩子进行交换即可,代码如下:

  4. #include
    using namespace std;
    typedef struct node
    {
    int val;
    node *lChild;
    node *rChild;
    node(int val)
    {
    this->val = val;
    this->lChild = nullptr;
    this->rChild = nullptr;
    }
    node()
    {
    this->lChild = nullptr;
    this->rChild = nullptr;
    }
    }TreeNode;
    TreeNode *createTree(int i, int intarr[], int length)
    {
    TreeNode *node = nullptr;
    if (i < length)
    {
    node = new TreeNode(intarr[i]);
    node->lChild = createTree(i * 2 + 1, intarr, length);
    node->rChild = createTree(i * 2 + 2, intarr, length);
    }
    return node;
    }
    void mirrorOfTree(TreeNode *root)
    {
    if (root == nullptr)//节点为空的时候,直接返回。
    {
    return;
    }
    else
    {
    TreeNode *nodetemp = root->lChild;//交换玩根节点的左右子树,再处理左右子树的交换。
    root->lChild = root->rChild;
    root->rChild = nodetemp;
    mirrorOfTree(root->lChild);
    mirrorOfTree(root->rChild);

    }
    }
    int main()
    {
    int intarr[6] = { 8,6,10,5,7,9 };
    TreeNode root = createTree(0, intarr, 6);
    mirrorOfTree(root);
    system(“pause”);
    return 0;
    }
    (2)类的指针和引用的基本操作
    #include
    using namespace std;
    class B
    {
    public:
    B()
    {
    cout << “construction of B” << endl;
    }
    void display()
    {
    cout << “this is a B” << endl;
    }
    };
    class SinlgeTest
    {
    public:
    static B& instance()//返回一个引用。
    {
    B instance_;
    return instance_;
    }
    static B
    instance_1()//引用转换为指针的操作。
    {
    return &instance();
    }
    };
    void display(B &b)//指针转换为引用的操作。
    {
    b.display();
    }
    int main()
    {
    auto b=SinlgeTest::instance();
    b.display();
    auto a = SinlgeTest::instance_1();
    a->display();
    display(*a);//指针转换为引用的操作。
    system(“pause”);
    return 0;
    }
    执行结果:如下图所示:
    在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值