您有两棵非常大的树:T1,有数百万个节点,T2,有数百个节点。创建一个算法来确定 T2 是否是 T1 的子树
作者给出了一个蛮力搜索的解决方案,就是一个节点一个节点比较。以下是代码:
boolean containsTree(TreeNode t1, TreeNode t2) {
if (t2 == null) return true;
else return subTree(t1, t2);
}
boolean subTree(TreeNode r1, TreeNode r2) {
if(r1 == null)
return false;
if(r1.data = r2.data){
if(matchTreee(r1, r2)) return true;
}
return ( subTree(r1.left, r2) || subTree(r1.right, r2) );
}
boolean matchTree(TreeNode r1, TreeNode r2){
if (r2 == null && r1 == null)
return true;
if (r1 == null || r2 == null)
return false; //big tree empty & subtree still not found
if (r1.data != r2.data)
return false;
return (matchTree(r1.left, r2.left) && matchTree(r1.right, r2.right));
}
在上面的代码中,我不同意函数的基本情况matchTree
if (r2 == null && r1 == null)
return true;
if (r1 == null || r2 == null)
return false; // big tree empty & subtree still not found
根据我的理解,基本情况应该是:
if(r2 == null) return true; //if r2 is null, r2 must match r1
no matter r1 is null or not
if(r1 == null) return false; //r1 == null means big tree empty
and we already know r2 != null, so r2 must not match r1.
大家可以帮我验证一下吗?
谢谢,