二叉树的包含情况
来源:互联网 发布:java se8 程序设计 编辑:程序博客网 时间:2024/04/28 16:20
判断一个二叉树是否包含另一个二叉树
package tree;/** * Created by Administrator on 2015/10/8 0008. */public class TreeContain { public static void main(String[] args) { int a[]={5,3,7,9,2,8}; int b[]={3}; BinaryTree root1=new BinaryTree(a[0]); BinaryTree root2=new BinaryTree(b[0]); for(int i=1;i<a.length;i++){ root1.insert(root1,a[i]); } for(int i=1;i<b.length;i++){ root2.insert(root2,b[i]); } /*root1.preTraval(root1); root2.preTraval(root2);*/ System.out.println(panduan(root1, root2)); } public static boolean panduan(BinaryTree root1, BinaryTree root2){ boolean flag=false; if(root1!=null&&root2!=null){ if(root1.value==root2.value) flag=deepPanduan(root1,root2); if(!flag) flag=panduan(root1.lchild,root2); if(!flag) flag=panduan(root1.rchild,root2); } return flag; } private static boolean deepPanduan(BinaryTree root1, BinaryTree root2) { if(root1==null) return false; else if(root2==null) return true; if(root1.value!=root2.value) return false; return deepPanduan(root1.lchild,root2.lchild)&&deepPanduan(root1.rchild,root2.rchild); /* if(root2.lchild==null&&root2.rchild!=null) return deepPanduan(root1.rchild,root2.rchild); if(root2.lchild!=null&&root2.rchild==null) return deepPanduan(root1.lchild,root2.lchild); return false;*/ }}
不知道是不是因为主函数树的构造关系,测试时,是根节点就会成功,如果有其他节点就会false
我知道了,就是在deepPanduan函数中,理应判断root2是否为空或者root1是否为空在进行返回值的确定,而上面所写的没有直接关系
if(root1==null) return false; else if(root2==null) return true;是不对的,理应是并列的
if(root2==null) return true; if(root1==null) return false;所以最终deepPanduan函数为:
private static boolean deepPanduan(BinaryTree root1, BinaryTree root2) { if(root2==null) return true; if(root1==null) return false; if(root1.value!=root2.value) return false; return deepPanduan(root1.lchild,root2.lchild)&&deepPanduan(root1.rchild,root2.rchild); }
哈哈,这样就可以了
0 0
- 二叉树的包含情况
- LeetCode—二叉树遍历的情况
- 检测二叉查找树节点的情况
- 二叉树情况总结
- 二叉树计算包含函数的中缀表达式
- 【数据结构】二叉树中包含的【堆栈、链表、队列】
- sql查询in包含null的情况
- poj 1145 二叉树和为某一值的情况
- 二叉搜索树的搜索和最值情况
- 遍历二叉树的三种情况-java实现
- 二叉树系列---求包含n个节点的二叉查找树的种类数
- 判断二叉树是否包含另一棵二叉树或者树的子结构
- 算法题:二叉树A是否包含二叉树B的拓扑结构
- 最小堆/哈希表/二叉树/平衡二叉树/红黑树的意义(什么情况下使用)
- 最小堆/哈希表/二叉树/平衡二叉树/红黑树的意义(什么情况下使用)
- 二叉树的相关算法(不包含线索二叉树、排序二叉树以及哈弗曼树,后序补上)
- 字符串的包含问题简单情况下的几个算法
- 判断两矩形是否交叉(包括包含的情况)
- c# random()函数用法
- 全世界最短IE判定if(!+[1,])的解释 VBArray
- 命名ACL的基本用法
- SAX和Dom解析XML的区别
- ALM
- 二叉树的包含情况
- java生成随机验证码
- eclipse 联想功能设置
- 一些常用git命令
- 第一部分 Java的类
- iOS7的后台多任务特性
- Hibernate用户指导系列一
- 深入讲解string和StringBuilder的区别
- superoj779 柠檬的密码