17、二叉树的镜像

题目描述:

  请完成一个函数,输入一个二叉树,该函数输出它的镜像。例如下图所示,左图是原二叉树,而右图则是该二叉树的镜像。
在这里插入图片描述

解题思路:

1. 先序遍历原二叉树的每个节点,如果遍历到的结点有子结点,就交换它的两个子结点;

2. 递归遍历每个节点的子节点,同样,如果遍历到的子节点有子节点,就交换它的两个子节点。
在这里插入图片描述

Demo:

class Solution {
public:
    void Mirror(TreeNode *pRoot) {
        if (pRoot == nullptr)
            return;
        // 叶子结点
        if (pRoot->left == nullptr && pRoot->right == nullptr)
            return;
        swap(pRoot->left, pRoot->right);
        if (pRoot->left)
            Mirror(pRoot->left);
        if (pRoot->right)
            Mirror(pRoot->right);
    }
};

猜你喜欢

转载自blog.csdn.net/daaikuaichuan/article/details/84899090
今日推荐