zoukankan      html  css  js  c++  java
  • LeetCode

    Symmetric Tree

    2014.1.1 01:12

    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

    For example, this binary tree is symmetric:

        1
       / 
      2   2
     /  / 
    3  4 4  3

    But the following is not:

        1
       / 
      2   2
          
       3    3

    Solution:

      Well..., I guess it's the new year 2014 now, and I've been writing blogs all night. Happy new year to those who are reading this article. Greetings from 2014, Beijing, China.

      To check if a tree is symmetric, you need to compare the corresponding nodes one pair at a time, in a recursive way.

      A pair at a time, therefore you need two TreeNode parameters in the recursive function.

      Time complexity is O(n), space complexity is O(1), where n is the number of nodes in the tree.

    Accepted code:

     1 //#define __MAIN__
     2 
     3 #ifdef __MAIN__
     4 #include <cstdio>
     5 #include <cstdlib>
     6 using namespace std;
     7 #endif
     8 
     9 /**
    10  * Definition for binary tree
    11  * struct TreeNode {
    12  *     int val;
    13  *     TreeNode *left;
    14  *     TreeNode *right;
    15  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    16  * };
    17  */
    18 
    19 #ifdef __MAIN__
    20 struct TreeNode {
    21     int val;
    22     TreeNode *left;
    23     TreeNode *right;
    24     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    25 };
    26 #endif
    27 
    28 class Solution {
    29 public:
    30     bool isSymmetric(TreeNode *root) {
    31         // Note: The Solution object is instantiated only once and is reused by each test case.
    32         if(root == nullptr){
    33             return true;
    34         }
    35         return isMirror(root->left, root->right);
    36     }
    37 private:
    38     bool isMirror(TreeNode *ra, TreeNode *rb) {
    39         if(ra == nullptr && rb == nullptr){
    40             return true;
    41         }
    42         
    43         if(ra == nullptr || rb == nullptr){
    44             return false;
    45         }
    46 
    47         if(ra->val == rb->val){
    48             return isMirror(ra->left, rb->right) && isMirror(ra->right, rb->left);
    49         }else{
    50             return false;
    51         }
    52     }
    53 };
  • 相关阅读:
    Spring相关知识点
    动态代理jdk和cglib的区别
    keepalived+nginx+tomcat+redis集群环境部署
    MongoDB_4.4 安装和配置
    vsCode 账号间同步 配置,插件
    vue 全局导航 router.beforeEach()
    网页左右两边元素高度自适应,两个元素高度一致,一面高度跟随另一面的高度变化而变化
    git 中 ssh key 的生成
    vscode html 自定义模板
    vscode vue 定义 单文件模板
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3500309.html
Copyright © 2011-2022 走看看