zoukankan      html  css  js  c++  java
  • LeetCode_Symmetric Tree

    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
    

    根开始,如果根节点的左右不对称,则false,否则,看根节点的左右子树是否对称。

    代码:(AC)

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
        public:
        bool left_right_Symmetric(TreeNode* pleft,TreeNode* pright)
    {
         if(pleft==NULL&&pright==NULL) return true;
          if(pleft==NULL&&pright!=NULL)return false;
          if(pleft!=NULL&&pright==NULL)return false;
          if(pleft->val!=pright->val) return false;
          return left_right_Symmetric(pleft->left,pright->right)&&left_right_Symmetric(pleft->right,pright->left);
    }
    public:
        bool isSymmetric(TreeNode* root) {
             if(root == NULL) return true;
        if(root->left!=NULL&&root->right==NULL) return false;
        if(root->left==NULL&&root->right!=NULL) return false;
        if(root->left!=NULL&&root->right!=NULL&&root->left->val!=root->right->val)return false;
        else return left_right_Symmetric(root->left,root->right);
        }
    };

    错误代码:没有理解对称树的概念。(WA)

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isSymmetric(TreeNode* root) {
        if(root==NULL) return true;
        if(root->left==NULL&&root->right!=NULL) return false;
        else if(root->left!=NULL&&root->right==NULL)return false;
             else if(root->left==NULL&&root->right==NULL) return true;
                  else if(root->left!=NULL&&root->right!=NULL&&root->left->val!=root->right->val) return false;
                       else if(root->left!=NULL&&root->right!=NULL&&root->left->val==root->right->val)
                       return isSymmetric(root->left)&&isSymmetric(root->right);
        }
    };




  • 相关阅读:
    【Vue前端】Vue前端注册业务实现!!!【代码】
    QQ第三方登录逻辑(微信,微博等同)
    发送短信验证码逻辑
    web图形验证码逻辑
    PID算法资料【视频+PDF介绍】
    如何配置电脑本地的域名
    js实现阻止默认事件preventDefault与returnValue
    js实现事件监听与阻止监听传播
    json字符串转换对象的方法1
    json字符串转换对象的方法
  • 原文地址:https://www.cnblogs.com/sunp823/p/5601434.html
Copyright © 2011-2022 走看看