【Leetcode】Symmetric Tree
2015-11-21 15:19
323 查看
题目链接:https://leetcode.com/problems/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:
But the following is not:
Note:
Bonus points if you could solve it both recursively and iteratively.
思路:
注意我在递归中保存结果的方式,跟Kth Smallest Element in a BST 算法2和Balanced Binary
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.
思路:
注意我在递归中保存结果的方式,跟Kth Smallest Element in a BST 算法2和Balanced Binary
Tree 中是一样的。
基本框架是:
boolean result = true; public boolean recur(TreeNode root){ if(root!=null){ if(satisfy a condition){ result = false; } recur(root.left); recur(root.right); } return result; }
算法:
public boolean isSym(TreeNode p, TreeNode q) { if (p == null && q == null) {//都为空 return true; }else if (p == null || q == null) {//有一个不为空 result = false; }else if (p.val == q.val) { isSym(p.left, q.right);//注意对称 isSym(p.right, q.left); } else { result = false; } return result; } public boolean isSymmetric(TreeNode root) { if (root == null) { return true; } if (root.left == null && root.right == null) { //单结点 return true; } if (root.left == null || root.right == null) {//不对称 return false; } return isSym(root.left, root.right); } boolean result = true;
相关文章推荐
- Android butterknife注解框架
- 实习小白::(转) Cocos2d-x 3.0 开发(十四)使用UIScrollView 实现大小不同物品拖动展示
- 用mdev使U盘中的脚本自动执行
- 实习小白::(转) Cocos2d-x 3.0开发(十三)使用CocoStudio编辑帧事件并关联到程序
- JS中offsetLeft,Left,clientLeft的区别
- 【栈,队列】两队列实现栈
- LINK1123:failure during conversion to COFF:file invalid or corrupt
- 实习小白::(转) Cocos2d-x 3.0 开发(十二)在CocoStudio中使用粒子挂载与曲线动画
- 基于Java的打包jar、war、ear包的作用与区别详解
- HDU 2602
- UITableView优化技巧
- eclipse安装hibernate插件
- 简单的单选多选按钮
- J2EE实验1:WEB基础
- 一道排列组合题
- jQuery学习笔记(五六)——高级事件
- 使用VIM插件ctags来阅读C代码
- 七周七种前端框架三: Angular2 印象
- 腾讯云CentOS7.0使用yum安装mysql及使用遇到的问题
- mysql 批量导入脚本