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

    思路:判断树是否是对称的 递归判断即可

    class Solution {
    public:
        bool isSymmetric(TreeNode* root) {
            if(NULL == root)   return true;
    
            TreeNode * L = root->left;
            TreeNode * R = root->right;
            return isSymmetricPart(L, R);
        }
    
         bool isSymmetricPart(TreeNode* L, TreeNode* R)
         {
             if(NULL == L && NULL == R) return true;
             if(NULL == L && NULL != R || NULL == R && NULL != L) return false;
             if(L->val == R->val)
                 return isSymmetricPart(L->left, R->right) && isSymmetricPart(L->right, R->left);
             else
                 return false;
             
         }
    };

    更简短的写法

    class Solution {
    public:
        bool isSymmetric(TreeNode* root) {
            return !root ? true : isSymmetricHelper(root->left, root->right);
        }
    
        bool isSymmetricHelper(TreeNode* left, TreeNode* right) {
            if (!left && !right) { return true; }
            return 
                (left && right) &&
                (left->val == right->val) &&
                isSymmetricHelper(left->left, right->right) &&
                isSymmetricHelper(left->right, right->left);
        }
    };
  • 相关阅读:
    New Skateboard
    Mike and strings
    C语言异或运算在程序设计中的妙用
    快速排序
    贪心算法
    快速排序过程分析
    深度搜索C语言伪代码
    matlab 中“newff” 函数的参数设置
    一维小波分解与去噪重构
    matlab绘图(详细)(全面)
  • 原文地址:https://www.cnblogs.com/dplearning/p/4627307.html
Copyright © 2011-2022 走看看