zoukankan      html  css  js  c++  java
  • 剑指 Offer 27. 二叉树的镜像

    我们从根节点开始,递归地对树进行遍历,并从叶子节点先开始翻转得到镜像。

    如果当前遍历到的节点 root 的左右两棵子树都已经翻转得到镜像,那么我们只需要交换两棵子树的位置,即可得到以 root 为根节点的整棵子树的镜像。

    /**
     * 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 nullptr;
            TreeNode* left = mirrorTree(root->left);
            TreeNode* right = mirrorTree(root->right);
            root->left = right;
            root->right = left;
            return root;
        }
    };
    
  • 相关阅读:
    每日日报1
    shazidouhui的使用体验
    水滴的使用体验
    麻雀记的使用体验
    钢镚儿的使用体验
    TD课程通的使用体验
    01 fs模块
    0 mysql 安装
    slot
    vue引入 lodash
  • 原文地址:https://www.cnblogs.com/fxh0707/p/15048373.html
Copyright © 2011-2022 走看看