• [leetcode.com]算法题目


    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
    

    Note:
    Bonus points if you could solve it both recursively and iteratively.

     1 /**
     2  * Definition for binary tree
     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     bool isSymmetric(TreeNode *root) {
    13         // Start typing your C/C++ solution below
    14         // DO NOT write int main() function
    15         if (!root) return true;
    16         
    17         if(!root->left && !root->right)
    18             return true;
    19             
    20         if(!root->left && root->right)
    21             return false;
    22         
    23         if(root->left && !root->right)
    24             return false;
    25             
    26         if(root->left->val == root->right->val)
    27             return symmetricTree(root->left, root->right);
    28         else
    29             return false;
    30     }
    31     
    32     bool symmetricTree(TreeNode *a, TreeNode *b){
    33         if(!a && !b)
    34             return true;
    35             
    36         if((!a && b) || (a && !b))
    37             return false;
    38             
    39         if(a->val == b->val)
    40             return symmetricTree(a->left, b->right) && symmetricTree(a->right, b->left);
    41         else
    42             return false;
    43     }
    44 };
    View Code

    思路:和判断两个tree是否相同有点类似,但是要注意这里判断的是是否对称。好久不写代码,看了别人写的这道题答案,感觉自己写的代码很不标准。不管怎样,先贴出来,慢慢进步吧。

  • 相关阅读:
    mongodb 配置单实例与双实例
    redis 集群 搭建
    memcached 搭建
    公网yum 源地址
    jdk 安装
    activemq 搭建--集群
    zookeeper 安装
    activemq 安装-单点
    rabbitmq 集群
    python——网络编程
  • 原文地址:https://www.cnblogs.com/xuning/p/3315546.html
Copyright © 2020-2023  润新知