我们数的结果,以及创建的类我们在
http://blog.csdn.net/cutter_point/article/details/48004301
已经从建过了,我们引入就可以了,不过 BinaryTreeNode里面的两个成员变量的权限最好改为public类型的,不然再写个get和set函数很麻烦,
毕竟java没有友元类这个玩意
/****************************************************************************************
*题目:树的子结构
* 输入两颗二叉树A和B,判断B是不是A的子结构。二叉树节点的定义如下。
*时间:2015年8月31日09:02:36
*文件:MergeLink.java
*作者:cutter_point
****************************************************************************************/
package bishi.Offer50.y2015.m08.d31;
import org.junit.Test;
//引入我们的树的结构
import bishi.Offer50.y2015.m08.d26.*;
public class HasSubTree
{
/**
* 用来比较两个树是否相同
* @param pRoot1
* @param pRoot2
* @return
*/
private boolean compare(BinaryTreeNode pRoot1, BinaryTreeNode pRoot2)
{
if(pRoot2 == null)
return true;
if(pRoot1 == null && pRoot2 != null)
return false;
//如果值不同,直接false
if(pRoot1.m_nValue != pRoot2.m_nValue)
return false;
//开始比较剩下的节点
return compare(pRoot1.m_pLeft, pRoot2.m_pLeft) && compare(pRoot1.m_pRight, pRoot2.m_pRight);
}
/**
* 比较两个树,看看pRoot1中是否含有pRoot2的子结构
* @param pRoot1
* @param pRoot2
* @return
*/
public boolean hasSubTree(BinaryTreeNode pRoot1, BinaryTreeNode pRoot2)
{
if(pRoot1 == null)
return false;
else if(pRoot1 != null && pRoot2 == null)
return true;
boolean result = false;
if(pRoot1.m_nValue == pRoot2.m_nValue)
{
//如果根相同,那么我们进行这颗树的比较
result = compare(pRoot1, pRoot2);
}//if
if(result == false)
{
//比较失败的话,我们就比较左边的子树
result = hasSubTree(pRoot1.m_pLeft, pRoot2);
}//if
if(result == false)
{
//左边比较失败,我们比较右边的
result = hasSubTree(pRoot1.m_pRight, pRoot2);
}//if
return result;
}
@Test
public void test()
{
//注意,这里我们根据前序和中序的方式创建树的话,是有问题的,因为我们的树不是排序二叉树
//也就是我们的树中有重复元素,我们构建这个树的时候并没有考虑到这点,光从序列上来说实现的难度略大
//以后有机会,我们再从新改过,2015年8月31日09:56:13
int preorder[] = {7,8,9,2,4,3,6}; //前序
int inorder[] = {9,8,4,2,3,7,6}; //中序
int preorder2[] = {8,9,2}; //前序
int inorder2[] = {9,8,2}; //中序
BinaryTree bt = new BinaryTree();
bt.construct(preorder, inorder);
BinaryTree bt2 = new BinaryTree();
bt.construct(preorder2, inorder2);
HasSubTree hst = new HasSubTree();
boolean hastree = false;
hastree = hst.hasSubTree(bt.root, bt2.root);
System.out.println(hastree);
}
}

被折叠的 条评论
为什么被折叠?



