• 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);
        }
    };




  • 相关阅读:
    SpringBoot配置文件(2)
    SpringBoot配置文件(1)
    java8新特性之stream流
    java8新特性之Lambda表达式
    zoj 1709 Oil Deposits
    zoj 2110 Tempter of the Bone
    poj 2823 Sliding Window
    fzu 1894 志愿者选拔
    hdoj 1754 I Hate It
    poj2404中国邮递员
  • 原文地址:https://www.cnblogs.com/sunp823/p/5601434.html
Copyright © 2020-2023  润新知