判断一个树是否为另一个树的子树
2016-04-22 11:22
316 查看
package search; import javax.swing.text.html.HTMLDocument.HTMLReader.IsindexAction; /* * @author: wjf * @version: 2016年4月22日 上午10:40:48 */ public class Tree { public boolean check(TNode root1,TNode root2){ if(root2==null){ return true; } if(root1==null){ return false; } if(root1.getValue() != root2.getValue()){ return false; }else{ return check(root1.getLeft(),root2.getLeft()) && check(root1.getRight(),root2.getRight()); } } public boolean isPartTree(TNode root1,TNode root2){ if(root2==null){ return true; } if(root1==null){ return false; } boolean result=false; if(root1.getValue() == root2.getValue()){ result=check(root1,root2); if(result)return true; } if(!result){ result=isPartTree(root1.getLeft(),root2); if(!result){ result=isPartTree(root1.getRight(),root2); } return result; } return false; } public static void main(String[] args){ TNode root1=new TNode(1); TNode c1=new TNode(1); TNode c2=new TNode(2); TNode c3=new TNode(3); root1.setLeft(c1); c1.setRight(c2); c1.setLeft(c3); TNode root2=new TNode(1); TNode c4=new TNode(2); TNode c5=new TNode(3); root2.setLeft(c5); root2.setRight(c4); Tree tree=new Tree(); System.out.println(tree.isPartTree(root1, root2)); System.out.println(tree.isPartTree(null, c2)); } } class TNode{ private int value; private TNode left=null; private TNode right=null; public TNode(int value){ this.value=value; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public TNode getLeft() { return left; } public void setLeft(TNode left) { this.left = left; } public TNode getRight() { return right; } public void setRight(TNode right) { this.right = right; } }
相关文章推荐
- php 实现购物车
- 论要不要重复造轮子
- 拖拽完美版2016/4/22
- PHP 文件处理手册
- linux 下使用 tc 模拟网络延迟和丢包(转)
- pycaffe学习
- actionbar
- 畅通工程续
- HID报告描述符解析_笔记
- linux echo 用法 【 -e \c 体会】
- NSInvocation使用实例
- C++第三次上机实验
- .Net4.0的网站在IE10、IE11出现“__doPostBack未定义”的解决办法
- kali更新2.0发现以前的源不能用解决方案
- 代码注释(code comments)
- Google数据中心B4网络具体实现
- mysql学习笔记(三)
- 第4次c++上机作业
- 如何使用CocoaPods
- tomcat手动启动闪退解决办法