【剑指Offer】面试题27. 二叉树的镜像

题目

请完成一个函数,输入一个二叉树,该函数输出它的镜像。

例如输入:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

镜像输出:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

示例 1:

输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]

限制:
0 <= 节点个数 <= 1000

本题同【LeetCode】226. 翻转二叉树

思路一:递归

自底向上。

代码

时间复杂度:O(n)
空间复杂度:O(n)

class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
        if (!root || (!root->left && !root->right)) return root;
        root->left = mirrorTree(root->left);
        root->right = mirrorTree(root->right);
        TreeNode *tmp = root->left;
        root->left = root->right;
        root->right = tmp;
        return root;
    }
};

另一种写法

自顶向下。
时间复杂度:O(n)
空间复杂度:O(n)

class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
        if (root) {
            TreeNode *tmp = root->left;
            root->left = root->right;
            root->right = tmp;
            root->left = mirrorTree(root->left);
            root->right = mirrorTree(root->right);
        }        
        return root;
    }
};

化简

class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
        if (root) {
            TreeNode *tmp = root->left;
            root->left = mirrorTree(root->right);
            root->right = mirrorTree(tmp);
        }        
        return root;
    }
};

思路二:迭代

层次遍历。
时间复杂度:O(n)
空间复杂度:O(n)

代码

class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
        if (root) {
            queue<TreeNode*> que;
            que.push(root);
            while (!que.empty()) {
                TreeNode *node = que.front();
                que.pop();
                TreeNode *tmp = node->left;
                node->left = node->right;
                node->right = tmp;
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
        }        
        return root;
    }
};

猜你喜欢

转载自www.cnblogs.com/galaxy-hao/p/12354917.html