你有两棵非常大的树:T1,有数百万个节点,T2, 有数百个节点。创建一个算法来确定T2是否为a 子树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.
你们能帮我核实一下吗?
谢谢,
答案 0 :(得分:1)
在我看来,本书的作者对T2 is a subtree of T1
的定义与您的定义不同。
例如,考虑下面的树(疯狂油漆技能):
作者的代码认为T3是T1的子树,但不是T2。你认为T2和T3都是T1的子树。
那就是说,我认为你的基础案例对'子树'的'自然'定义更有意义。
C#测试代码(data
类型为int
):
var t1 = new TreeNode() { data = 0,
left = new TreeNode() { data = 1,
left = new TreeNode() { data = 2 },
right = new TreeNode() { data = 3,
right = new TreeNode() { data = 4 } } } };
var t2 = new TreeNode() { data = 1,
left = new TreeNode() { data = 2 },
right = new TreeNode() { data = 3 } };
var t3 = new TreeNode() { data = 1,
left = new TreeNode() { data = 2 },
right = new TreeNode() { data = 3,
right = new TreeNode() { data = 4 } } };