LeetCode(101)Symmetric Tree
2015-10-01 17:32
441 查看
题目
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); } } };
相关文章推荐
- #个人博客作业Week3——必应词典案例分析
- OpengGL第八版的第一个例子
- android问题集锦之一
- 齐达迪的第一篇博客
- ion torrent ion proton
- 合成和聚合的关系
- declare aa char(5) := 'b'; begin dbms_output.put_line(aa || '00'); end;
- A time to be promoted
- Aizu 2303 Marathon Match (概率)
- Android Studio如何引用jar包裹(不gradle)
- 黑马程序员——java学习笔记--日期操作类
- 快速排序
- C语言及程序设计.第二十三课.项目3.两段函数求值
- ThinkPHP控制器
- 黑马程序员——java学习笔记--正则表达式
- 关于Linux系统的平均负载最全面介绍
- 【点到线段距离】URAL - 1348 Goat in the Garden 2
- 无法关闭的QT程序(覆盖closeEvent,新建QProcess并脱离关系)
- 为arm内核构建源码树----Linux内核剖析(四)
- WINCC7.0下用户归档的查询与导出——导出篇