《剑指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

代码(递归)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
         if(!root)return NULL;
         TreeNode *tmp = root->left;
         root->left = mirrorTree(root->right);
         root->right = mirrorTree(tmp);
         return root;
    }
};

结果:

执行用时 :4 ms, 在所有 C++ 提交中击败了64.96%的用户
内存消耗 :9.1 MB, 在所有 C++ 提交中击败了100.00%的用户

代码(非递归)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
        if(!root)return NULL;
         queue<TreeNode*> q;
        q.push(root);
        TreeNode* tmp1,*tmp2;
        while(!q.empty())
        {
            tmp1 = q.front();
            q.pop();
            tmp2 = tmp1->left;
            tmp1->left = tmp1->right;
            tmp1->right = tmp2;
            if(tmp1->right)q.push(tmp1->right); 
            if(tmp1->left)q.push(tmp1->left); 
        }
         return root;
    }
};

结果:

执行用时 :4 ms, 在所有 C++ 提交中击败了64.86%的用户
内存消耗 :9.5 MB, 在所有 C++ 提交中击败了100.00%的用户
posted @ 2020-04-16 10:03  曲径通霄  阅读(94)  评论(0编辑  收藏  举报