等价二叉树
2016-05-31 17:57
267 查看
检查两棵二叉树是否等价。等价的意思是说,首先两棵二叉树必须拥有相同的结构,并且每个对应位置上的节点上的数都相等。
样例
就是两棵等价的二叉树。
就不是等价的。【递归判断】
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param a, b, the root of binary trees.
* @return true if they are identical, or false.
*/
public boolean isIdentical(TreeNode a, TreeNode b) {
// Write your code here
if (a == null && b == null){
return true;
}
if ((a == null && b != null) || (a != null && b == null) || (a.val != b.val)){
return false;
}
boolean left = isIdentical(a.left, b.left);
boolean right = isIdentical(a.right, b.right);
//切记!左右子树都相等才可以!
return left && right;
}
}
样例
1 1 / \ / \ 2 2 and 2 2 / / 4 4
就是两棵等价的二叉树。
1 1 / \ / \ 2 3 and 2 3 / \ 4 4
就不是等价的。【递归判断】
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param a, b, the root of binary trees.
* @return true if they are identical, or false.
*/
public boolean isIdentical(TreeNode a, TreeNode b) {
// Write your code here
if (a == null && b == null){
return true;
}
if ((a == null && b != null) || (a != null && b == null) || (a.val != b.val)){
return false;
}
boolean left = isIdentical(a.left, b.left);
boolean right = isIdentical(a.right, b.right);
//切记!左右子树都相等才可以!
return left && right;
}
}
相关文章推荐
- 第14周阅读程序1(3)
- Kvm启动ubuntu虚拟机无法ssh
- 通过使用evercookie技术实现设备指纹
- 如何暂停和恢复CALayer上的动画
- hdu-2037-今年暑假不AC-简单DAG
- android 多线程同步-synchronized关键字
- eclipse v4.5.2+maven 3.3.9配置web项目
- Debug---Eclipse断点调试基础
- easyui 中 的同步树(2)
- iOS系统自带的 UIAlertView 自动旋转的实现
- sudo配置文件/etc/sudoers详解及实战用法
- Zend Studio 自动换行
- MAC 如何使用Github Desktop 客户端
- APK文件使用ApkTool解包反编译和重新打包及签名
- A+B Problem (64bit Integer + EOF)
- javascript 的module 模块化
- 内存泄露从入门到精通三部曲之二 --- 排查方法篇
- UEditor富文本编辑框学习
- sqlite删除与当前时间差值在10秒以上的记录
- iOSAPP启动时实现加载广告