题目解析:查询B树是否是A树的子结构
代码:
package demo4;
/**
* Created by Administrator on 2018/12/6.
* 树节点
*/
class Node {
int data;
Node left;
Node right;
public Node(int data){
this.data=data;
this.left=null;
this.right=null;
}
}
package demo4;
/**
* Created by Administrator on 2018/12/6.
* 新建树
*/
public class BinaryTree {
public Node root=null;
public void insert(int data){
Node newNode=new Node(data);
if(root==null){
root=newNode;
}else {
Node current=root;
Node parent;
while (true){
parent=current;
if(data<=current.data){
current=current.left;
if(current==null){
current=newNode;
return;
}
}else{
current=current.right;
if(current==null){
current=newNode;
return;
}
}
}
}
}
public void BulidTree(int[] data){
for(int i=0;i<data.length;i++){
insert(data[i]);
}
}
}
package demo4;
/**
* Created by Administrator on 2018/12/6.
* root1与root2进行匹配
*/
public class SubTree {
public boolean hasSubTree(Node root1,Node root2){
if(root1==null&&root2!=null)
return false;
if(root2==null)
return false;
boolean flag=false;
if(root1!=null&&root2!=null){
if(root1.data==root2.data)
flag=DoesHas(root1,root2);
if(!flag)
flag=hasSubTree(root1.right,root2);
if(!flag)
flag=hasSubTree(root1.left,root2);
}
return flag;
}
/**
private boolean DoesHas(Node root1,Node root2){
if(root1==null&&root2!=null)
return false;
if(root2==null)
return false;
if(root1.data!=root2.data)
return false;
return DoesHas(root1.left,root2.left)&&DoesHas(root1.right,root2.right);
}
*/
//以上的第一行与第二行代码判断错误
private boolean DoesHas(Node root1,Node root2){
if(root2==null)
return true;
if(root1==null&&root2!=null)
return false;
if(root1.data==root2.data){
return DoesHas(root1.left,root2.left)&&DoesHas(root1.right,root2.right);
}else {
return false;
}
}
}
package demo4;
/**
* Created by Administrator on 2018/12/6.
* 进行测试
*/
public class SubTreeTest {//测试代码
public static void main(String args[]){
BinaryTree biTree1=new BinaryTree();
BinaryTree biTree2=new BinaryTree();
int[] data1={2,8,5,6,1,3,9};
int[] data2={2,1,8};
biTree1.BulidTree(data1);
biTree2.BulidTree(data2);
SubTree sub=new SubTree();
boolean result=(sub.hasSubTree(biTree1.root,biTree2.root));
System.out.println(result);
}
}
结果: