zoukankan      html  css  js  c++  java
  • 【剑指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;
        }
    };
    
  • 相关阅读:
    linux 环境变量
    Java finally语句到底是在return之前还是之后执行?
    JAVA NIO之浅谈内存映射文件原理与DirectMemory
    cpu架构
    tomcat 安装
    linux 下载rpm包到本地,createrepo:创建本地YUM源
    linux下查看和添加PATH环境变量
    virtualbox 相关操作
    空间叠加分析
    java程序的加载与执行
  • 原文地址:https://www.cnblogs.com/galaxy-hao/p/12354917.html
Copyright © 2011-2022 走看看