[leetcode.com]算法题目 - 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.

复制代码
 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         // Start typing your C/C++ solution below
14         // DO NOT write int main() function
15         if (!root) return true;
16         
17         if(!root->left && !root->right)
18             return true;
19             
20         if(!root->left && root->right)
21             return false;
22         
23         if(root->left && !root->right)
24             return false;
25             
26         if(root->left->val == root->right->val)
27             return symmetricTree(root->left, root->right);
28         else
29             return false;
30     }
31     
32     bool symmetricTree(TreeNode *a, TreeNode *b){
33         if(!a && !b)
34             return true;
35             
36         if((!a && b) || (a && !b))
37             return false;
38             
39         if(a->val == b->val)
40             return symmetricTree(a->left, b->right) && symmetricTree(a->right, b->left);
41         else
42             return false;
43     }
44 };
View Code
复制代码

思路:和判断两个tree是否相同有点类似,但是要注意这里判断的是是否对称。好久不写代码,看了别人写的这道题答案,感觉自己写的代码很不标准。不管怎样,先贴出来,慢慢进步吧。

posted on   Horstxu  阅读(191)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示