zoukankan      html  css  js  c++  java
  • 101. Symmetric Tree

    1. 问题描述

    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

    For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
    
       1
      / 
      2   2
     /   / 
     3  4 4   3
    But the following [1,2,2,null,3,null,3] is not:
     1
    / 
    2  2
        
      3   3

    Note:

    Bonus points if you could solve it both recursively and iteratively.
    Tags: Tree Depth-first Search Breadth-first Search

    2. 解题思路
    3. 代码

    class Solution {
    public:
        bool isSymmetric(TreeNode* root) 
        {
            if (!root)
            {
                return true;
            }
            if (NULL != root->left && NULL != root->right)
            {
                return isSymme(root->left, root->right);
            }
            else if (NULL == root->left && NULL == root->right)
            {
                return true;
            }
            else
            {
                return false;    
            }
        }
    private:
        bool isSymme(TreeNode* lh, TreeNode* rh)
        {
            if (NULL == lh && NULL == rh)
            {
                return true;
            }
            else if (NULL != lh && NULL != rh)
            {
                if (lh->val != rh->val)
                {
                    return false;
                }
                else
                {
                    return isSymme(lh->left, rh->right) && isSymme(lh->right, rh->left);
                }
            }
            else
            {
                return false;
            }        
        }
    };

    4. 反思

  • 相关阅读:
    IntelliJ IDEA基本设置
    git安装
    Git的作用与安装
    git是什么
    SpringMVC控制器类方法的返回值
    SpringMVC中Model机制
    什么是Nosql
    如何使用Jedis操作redis
    redis中数据类型操作命令
    redis的全局命令
  • 原文地址:https://www.cnblogs.com/whl2012/p/5791579.html
Copyright © 2011-2022 走看看