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;
        }
    };
    
  • 相关阅读:
    Xen虚拟机的创建和启动
    Linux Shell编程基础
    虚拟化的概念
    Android XML解析
    Android数据存储之文件存储
    Android GPRS开关软件(APN开关)
    数据中心
    debian下dos2unix的安装
    linux Shell重定向
    GPRS开关软件一些问题的解决方法
  • 原文地址:https://www.cnblogs.com/galaxy-hao/p/12354917.html
Copyright © 2011-2022 走看看