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;
        }
    };
    
  • 相关阅读:
    零基础学python-2.7 列表与元组
    什么是App加壳,以及App加壳的利与弊
    Linux tar包安装Nginx
    GT背靠背onsite
    编程算法
    DELPHI动态创建窗体
    扩展名为DBF的是什么文件啊?
    异构数据库之间完全可以用SQL语句导数据
    XP局域网访问无权限、不能互相访问问题的完整解决方案
    Delphi 之 菜单组件(TMainMenu)
  • 原文地址:https://www.cnblogs.com/galaxy-hao/p/12354917.html
Copyright © 2011-2022 走看看