[剑指offer]JT18---二叉树的镜像(树的镜像也是递归)

剑指offer第十八题

题目如下

在这里插入图片描述

思路与代码

就是将树的左右支交换便可以了
交换用到了递归,分治的思想

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
    
    
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return TreeNode类
     */
    TreeNode* Mirror(TreeNode* pRoot) {
    
    
        // write code here
        if(pRoot==NULL)
            return pRoot;
        else
            swap(pRoot->left,pRoot->right);
        Mirror(pRoot->left);
        Mirror(pRoot->right);
        return pRoot;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_42136832/article/details/114519628
今日推荐