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




  • 相关阅读:
    qcow2文件压缩
    raw格式镜像文件压缩并转换为qcow2格式
    centos7 install virt-sysprep
    镜像简介
    QEMU 使用的镜像文件:qcow2 与 raw
    ubuntu14.04中国源
    less css下载及编绎工具
    分布式计算中WebService的替代方案: RPC (XML-RPC | JSON-RPC)
    Asp.net WebServer
    C#取调用堆栈StackTrace
  • 原文地址:https://www.cnblogs.com/sunp823/p/5601434.html
Copyright © 2011-2022 走看看