zoukankan      html  css  js  c++  java
  • LeetCode 101 Symmetric Tree 判断一颗二叉树是否是镜像二叉树

    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.

     1 /**
     2  * Definition for a binary tree node.
     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==nullptr)
    14             return true;
    15         return helper(root->left,root->right);
    16     }
    17     bool helper(TreeNode* left,TreeNode* right)
    18     {
    19         if(!left&&!right)
    20             return true;
    21         else if(!left||!right)
    22             return false;
    23         else if(left->val!=right->val)
    24             return false;
    25         else
    26             return helper(left->left,right->right)&&helper(left->right,right->left);
    27     }
    28 };
  • 相关阅读:
    洛谷 U140360 购物清单
    洛谷 U140359 批量处理
    洛谷 U140358 操作系统
    洛谷U140357 Seaway连续
    洛谷 U141394 智
    洛谷 U141387 金
    CF1327F AND Segments
    刷题心得—连续位运算题目的小技巧
    CF743C Vladik and fractions
    洛谷 P6327 区间加区间sin和
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8572544.html
Copyright © 2011-2022 走看看