LeetCode(101)Symmetric Tree
2024-08-30 16:42:26
题目
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
But the following is not:
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what “{1,#,2,3}” means? > read more on how binary tree is serialized on OJ.
分析
判断一棵二叉树是否为对称树;
仍然采用递归的思想,判断该树的左右子树是否对称;
若二叉树p与二叉树q对称,也就是说其根节点相同,p左子树应与q右子树对称,同理,p右子树应与q左子树对称;
AC代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if (!root)
return true;
else
//判断左右子树是否对称
return isSymmetricTree(root->left, root->right);
}
bool isSymmetricTree(TreeNode* p, TreeNode* q) {
//如果两个二叉树均为空,则返回true
if (!p && !q)
{
return true;
}
//如果两者其一为空树,则返回false
else if (!p || !q)
{
return false;
}
else{
if (p->val != q->val)
return false;
else
//p左子树应与q右子树对称,同理,p右子树应与q左子树对称
return isSymmetricTree(p->left, q->right) && isSymmetricTree(p->right, q->left);
}
}
};
最新文章
- 学习ASP.NET Core,怎能不了解请求处理管道[2]: 服务器在管道中的“龙头”地位
- 最好的5个Android ORM框架
- C#设计模式之工厂方法
- information_schema系列之字符集校验(CHARACTER_SETS,COLLATIONS,COLLATION_CHARACTER_SET_APPLICABILITY)
- How to control PrincipalObjectAccess table growth in Microsoft Dynamics CRM 2011
- C++之枚举
- PGA与SGA
- grawlew 编译
- A Game of Thrones(7) -Arya
- 强悍的跨平台开源多媒体中心XBMC介绍
- vue 手机端开发 小商铺 添加购物车 以及结算 功能
- loadrunner场景之集合点设置技巧
- HDU 2516 斐波那契博弈
- 洛谷P2918 [USACO08NOV]买干草(一道完全背包模板题)
- HEOI2013 Segment
- P1025 数的划分 dfs dp
- WebApi 后台获取token值
- vue实现添加与删除图书
- hdoj:2031
- Flex组件参考 代码参考汇总
热门文章
- hdu3926 Hand in Hand 同构图
- Android课程设计第二天界面排版
- 贪心 Codeforces Round #304 (Div. 2) B. Soldier and Badges
- 【转】java序列化一定要应该注意的6个事项!
- Bloom Filter概念和原理【转】
- Android手机app耗电量测试工具 - Gsam Battery Monitor
- JavaScript 的垃圾回收与内存泄露
- # Transition:添加弹出过渡效果
- Java三大特性之封装
- Types of Security Vulnerabilities