zoukankan      html  css  js  c++  java
  • [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是否相同有点类似,但是要注意这里判断的是是否对称。好久不写代码,看了别人写的这道题答案,感觉自己写的代码很不标准。不管怎样,先贴出来,慢慢进步吧。

  • 相关阅读:
    开源:不断创新的动力
    Inkpad中文翻译已合并到官方项目
    Inkpad绘图原理浅析
    Vectoroid
    发布大幅重构优化的 TouchVG 1.0.2
    清理掉一直想研究的开源项目
    函数指针调用方式
    音视频直播优化
    std::unique_lock与std::lock_guard区别示例
    c++容器的操作方法总结
  • 原文地址:https://www.cnblogs.com/xuning/p/3315546.html
Copyright © 2011-2022 走看看