• [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
    

    Note:
    Bonus points if you could solve it both recursively and iteratively.

    Note:子树不需要对称,只需要根书的左右是镜像即可。

    1 递归,判断leftNode->left和rightNode->right,leftNode->right和rightNode->left,left->val == right->val

     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) return true;
    14             return isSymmetricTree(root->left, root->right);
    15         }
    16 
    17         bool isSymmetricTree(TreeNode *left, TreeNode *right)
    18         {
    19             if(left == NULL && right == NULL) return true; //终止条件
    20             if(left == NULL || right == NULL) return false;
    21             if(left->val == right->val &&          //合并
    22                     isSymmetricTree(left->left, right->right) &&
    23                     isSymmetricTree(right->left, left->right) 
    24               )   
    25                 return true;
    26 
    27             return false;
    28         }
    29 
    30 };
  • 相关阅读:
    20170417列表的count计数、index、reverse、sort函数
    (一)grpc-创建一个简单的grpc 客户端和服务器
    通用装饰器
    Git学习(一):Git介绍、仓库和分支等基本概念解释
    APP测试
    接口测试用例设计
    笔记整理
    接口测试
    gzip -压缩与解压缩
    declare 命令 -声明shell 变量
  • 原文地址:https://www.cnblogs.com/diegodu/p/3780446.html
Copyright © 2020-2023  润新知