LeetCode题解:Same Tree
2015-08-28 10:24
267 查看
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
题意:给定两颗二叉树,判断它们是否相同
解题思路:层次遍历
代码:
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
题意:给定两颗二叉树,判断它们是否相同
解题思路:层次遍历
代码:
public class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { boolean result = false; if(p == null && q == null){ return true; } if(p == null ||q == null){ return false; } Queue<TreeNode> pQueue = new LinkedList<TreeNode>(); Queue<TreeNode> qQueue = new LinkedList<TreeNode>(); pQueue.add(p); qQueue.add(q); while(!pQueue.isEmpty() && !qQueue.isEmpty()){ TreeNode tempP = pQueue.poll(); TreeNode tempQ = qQueue.poll(); if(tempP == null && tempQ == null){ result = true; } if(tempP == null || tempQ ==null){ result = false; } if(tempP.val != tempQ.val){ result = false; break; }else{ result = true; } if(tempP.left != null){ pQueue.add(tempP.left); } if(tempP.right != null){ pQueue.add(tempP.right); } if(tempQ.left != null){ qQueue.add(tempQ.left); } if(tempQ.right != null){ qQueue.add(tempQ.right); } if(pQueue.size() != qQueue.size()){ result = false; break; } } return result; } }
相关文章推荐
- 浅析C#(WPF)中的Application类
- jquery的promise处理嵌套请求
- 计算机组成原理三:总线
- jquery实现多条件筛选特效代码分享
- Hive运行
- LeetCode题解:Maximum Depth of Binary Tree
- C#学习笔记---如何提高代码逼格
- Scala学习笔记(六):Scala程序
- HDU 3836
- ios获取当前屏幕所显示Controller
- Oracle AWR报告指标全解析(三)
- 电脑数据怎么恢复
- 字体颜色的输出
- linux命令中分页等管道符的使用
- 0006 手动定制原版 Win7 操作系统(五)
- java在acm中的使用
- 双色球初探
- 软件测试学习笔记---阿冬专栏
- 基础数据校验和性能数据BSC条数缺失
- 在linux的驱动Makefile中添加调试选项