• LeetCode OJ


    题目:

    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 judge(TreeNode *p_left, TreeNode *p_right) {
    13         if (p_left == NULL && p_right == NULL) {
    14             return true;
    15         } else if ((p_left != NULL && p_right == NULL) || (p_left == NULL && p_right != NULL)) {
    16             return false; 
    17         }
    18         
    19         if (p_left->val != p_right->val) return false;
    20         
    21         if ((p_left->left != p_right->right && (p_left->left == NULL || p_right->right == NULL)) ||
    22             (p_left->right != p_right->left && (p_left->right == NULL || p_right->left == NULL))) {
    23                 return false;
    24         }
    25 
    26         return judge(p_left->left, p_right->right) && judge(p_left->right, p_right->left); 
    27         
    28     }
    29     bool isSymmetric(TreeNode *root) {
    30         if (root == NULL || (root->left == NULL && root->right == NULL)) {
    31             return true;
    32         } else if (root->left == NULL || root->right == NULL) {
    33             return false;
    34         } 
    35         if (root->left->val == root->right->val) {
    36             return judge(root->left, root->right);
    37         }
    38         return false;
    39     }
    40 };
  • 相关阅读:
    Asp.net Core依赖注入(Autofac替换IOC容器)
    .NET Core WEB API接口参数模型绑定
    .net core docker容器编排部署(linux)
    asp .net core发布订阅kafka
    asp.net Core依赖注入(自带的IOC容器)
    VS2017 GIT推送错误:Authentication failed解决办法
    《ASP.NET Core 开发实战》
    《Entity Framework 实用精要》
    《C# 敏捷开发实践》
    《ASP.NET 框架应用程序实战》
  • 原文地址:https://www.cnblogs.com/dongguangqing/p/3728285.html
Copyright © 2020-2023  润新知