zoukankan      html  css  js  c++  java
  • 剑指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]

    关键在于发现二叉树的镜像其实可以直接通过交换左右子树达成,采用递归的方法,先完成左右子树的镜像,再交换左右子树。

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     TreeNode* mirrorTree(TreeNode* root) {
    13         return recursive_exchange(root);
    14     }
    15 
    16     TreeNode* recursive_exchange(TreeNode* cur){
    17         if(cur==nullptr)
    18             return nullptr;
    19         cur->left=recursive_exchange(cur->left);
    20         cur->right=recursive_exchange(cur->right);
    21         TreeNode* temp=cur->left;
    22         cur->left=cur->right;
    23         cur->right=temp;
    24         return cur;
    25     }
    26 };
  • 相关阅读:
    区块链
    黑帽内容整理
    编程语言
    编程语言
    PHP
    安全体系建设-OWASP
    burp
    编程语言-Python-GUI
    加解密
    结合自己的程序对thinkphp模板常量的理解
  • 原文地址:https://www.cnblogs.com/rookiez/p/13233769.html
Copyright © 2011-2022 走看看