题目

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);
}
}
};

最新文章

  1. 学习ASP.NET Core,怎能不了解请求处理管道[2]: 服务器在管道中的“龙头”地位
  2. 最好的5个Android ORM框架
  3. C#设计模式之工厂方法
  4. information_schema系列之字符集校验(CHARACTER_SETS,COLLATIONS,COLLATION_CHARACTER_SET_APPLICABILITY)
  5. How to control PrincipalObjectAccess table growth in Microsoft Dynamics CRM 2011
  6. C++之枚举
  7. PGA与SGA
  8. grawlew 编译
  9. A Game of Thrones(7) -Arya
  10. 强悍的跨平台开源多媒体中心XBMC介绍
  11. vue 手机端开发 小商铺 添加购物车 以及结算 功能
  12. loadrunner场景之集合点设置技巧
  13. HDU 2516 斐波那契博弈
  14. 洛谷P2918 [USACO08NOV]买干草(一道完全背包模板题)
  15. HEOI2013 Segment
  16. P1025 数的划分 dfs dp
  17. WebApi 后台获取token值
  18. vue实现添加与删除图书
  19. hdoj:2031
  20. Flex组件参考 代码参考汇总

热门文章

  1. hdu3926 Hand in Hand 同构图
  2. Android课程设计第二天界面排版
  3. 贪心 Codeforces Round #304 (Div. 2) B. Soldier and Badges
  4. 【转】java序列化一定要应该注意的6个事项!
  5. Bloom Filter概念和原理【转】
  6. Android手机app耗电量测试工具 - Gsam Battery Monitor
  7. JavaScript 的垃圾回收与内存泄露
  8. # Transition:添加弹出过渡效果
  9. Java三大特性之封装
  10. Types of Security Vulnerabilities