题目:

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.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

代码:

/**
* 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;
stack<TreeNode *> staL, staR;
staL.push(root->left);
staR.push(root->right);
while ( !staL.empty() && !staR.empty() )
{
TreeNode *tmpL = staL.top();
staL.pop();
TreeNode *tmpR = staR.top();
staR.pop();
if ( !tmpL && !tmpR ) continue;
if ( !tmpL || !tmpR ) return false;
if ( tmpL->val != tmpR->val ) return false;
staL.push(tmpL->right);
staL.push(tmpL->left);
staR.push(tmpR->left);
staR.push(tmpR->right);
}
return staL.empty() && staR.empty();
}
};

tips:

深搜思想。设立两个栈:左栈和右栈。

从根节点开始:左子树用左栈遍历(node->left->right);右子树用右栈遍历(node->right->left)。

这样就可以转化为Same Tree这道题了(http://www.cnblogs.com/xbf9xbf/p/4505032.html

最新文章

  1. SharePoint Online 创建门户网站系列之准备篇
  2. 忙了好一阵,今天随便写篇关于canvas的小东西
  3. 甘特图和PERT图
  4. Nginx学习笔记(九) 配置文件详细说明
  5. [Tips] Useful link ... on going
  6. 拿到内存中dom元素的最后样式进行修改obj下的currentStyle方法
  7. linux扩展权限
  8. Code Smell那么多,应该先改哪一个?
  9. AgileEAS.NET SOA中间件平台/敏捷软件开发平台 and SQL详解
  10. ECMAScript5.1的运算符、类型转换总结
  11. arcengine导出复本
  12. 【一】java 虚拟机 监控示例 Eclipse Memory Analyser
  13. C# 正则表达式匹配盘符
  14. 生产案例、Linux出现假死,怎么回事?
  15. .Net Core 自定义配置源从配置中心读取配置
  16. Metapackage包
  17. appache 端口 更改
  18. 【.Net】C# 反编译工具之dnSpy
  19. Office Developer Tools for Visual Studio 2012现在可用了
  20. If,for,range混合使用笔记-(VBA视频教程2:使用IF进行逻辑判断)

热门文章

  1. c3p0配置xml
  2. 发送Ajax请求获取JSON格式数据
  3. Data Being Added Conflicts with Existing Data
  4. silverlight获取web的url参数
  5. linux 常用命令及技巧
  6. android学习视频分享
  7. 一款jQuery满屏自适应焦点图切换特效
  8. Yii框架中使用PHPExcel导出Excel文件
  9. SharePoint ribbon icons disappeared(网站顶部Top bar 齿轮图标,以及编辑模式下Ribbon中Icon消失)
  10. Java 第七天 动态代理