剑指offer 二叉树的镜像 c++

题目描述

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

输入描述

剑指offer 二叉树的镜像 c++_第1张图片

代码

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 == nullptr) return;
        if(pRoot->left == nullptr && pRoot->right == nullptr) return;
        //交换节点
        TreeNode* temp = pRoot->left;
        pRoot->left = pRoot->right;
        pRoot->right = temp;
        //递归法
        if(pRoot->left != nullptr) Mirror(pRoot->left);
        if(pRoot->right != nullptr) Mirror(pRoot->right);
    }
};

你可能感兴趣的:(二叉树)