You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This solution can be improved from O(n*m) to O(n + m), where n is the size of the big tree t1 and m is size of the small tree t2. We can get the size of every subtree of t1 in O(n) and size of t2 in O(m), and then only compare the subtrees of size m in t1 with t2. There are at most n/m subtrees of size m, and each compare costs O(m), so the total cost is O(n/m * m) + O(n) + O(m) = O(n + m).
publicstaticbooleancontainsTree(TreeNodet1, TreeNodet2) {
if (t2 == null) {
returntrue; // The empty tree is a subtree of every tree.
}
boolean[] result = newboolean[1];
// Get the size of t2intm = treeSizeAndMatch(t2, null, -1, null);
// Get the size of t1 and do the match for subtrees of size mintn = treeSizeAndMatch(t1, t2, m, result);
returnresult[0];
}
privatestaticinttreeSizeAndMatch(TreeNoder1, TreeNoder2, intmatchSize, boolean[] result)
{
if(r1 == null) return0;
intleftSize = treeSizeAndMatch(r1.left, r2, matchSize, result);
intrightSize = treeSizeAndMatch(r1.right, r2, matchSize, result);
intsize = 1 + leftSize + rightSize;
if(size == matchSize && !result[0]) {
result[0] = matchTree(r1,r2);
}
returnsize;
}
//The same as Q4_10_Check_Subtree/QuestionB.matchTreepublicstaticbooleanmatchTree(TreeNoder1, TreeNoder2) { ... }
The text was updated successfully, but these errors were encountered:
This solution can be improved from O(n*m) to O(n + m), where n is the size of the big tree t1 and m is size of the small tree t2. We can get the size of every subtree of t1 in O(n) and size of t2 in O(m), and then only compare the subtrees of size m in t1 with t2. There are at most n/m subtrees of size m, and each compare costs O(m), so the total cost is O(n/m * m) + O(n) + O(m) = O(n + m).
The text was updated successfully, but these errors were encountered: