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

    题解:递归的解法,重新写一个递归函数bool issysmem(TreeNode *lc,TreeNode &rc),函数输入分别输入待比较是否对称的两个树的树根。首先比较这两棵树根的值是否相等,然后递归的比较lc的左子和rc的右子,以及lc的右子和rc的左子是否对称。代码如下:
     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     bool isSymmetric(TreeNode *root) {
    13         if(root == NULL)
    14             return true;
    15         return issysmem(root->left,root->right);
    16     }
    17     bool issysmem(TreeNode *lc,TreeNode *rc){
    18         if((!lc && rc) || (lc && !rc))
    19             return false;
    20         if(lc == NULL && rc == NULL)
    21             return true;
    22         if(lc->val != rc->val)
    23             return false;
    24         return issysmem(lc->left,rc->right) && issysmem(lc->right,rc->left);
    25     }
    26 };
  • 相关阅读:
    从头学Android之Android布局管理:LinerLayout线性布局
    Android onTouch事件传递机制
    android开源项目和框架
    <hdu
    <hdu
    <poj
    <poj
    <hdu
    <hdu
    <hdu
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3779044.html
Copyright © 2011-2022 走看看