《剑指offer》二叉树的镜像

一、题目描述

操作给定的二叉树,将其变换为源二叉树的镜像。

二、输入描述

二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11

三、输出描述

镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5

四、牛客网提供的框架

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/
class Solution {
public:
    void Mirror(TreeNode *pRoot) {

    }
};

五、解题思路

使用递归方法。把结点的左子树、右子树掉换,递归执行(两个子树)。

六、代码

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/
class Solution {
public:
    void Mirror(TreeNode *pRoot) {
        if(pRoot)
        {
            TreeNode *temp;
            temp = pRoot->left;
            pRoot->left = pRoot->right;
            pRoot->right = temp;
            Mirror(pRoot->left);
            Mirror(pRoot->right);
        }

    }
};

七、总结

posted @ 2016-06-30 00:07  chenximcm  阅读(107)  评论(0编辑  收藏  举报