我将分两步解决这个问题:
A查找in的根B(DFS 的任一 BFS)
- 使用递归算法验证它
A包含在B(给出该起始节点)中,如下所示(我编造了相同的疯狂伪语言,因为您没有指定语言。我认为这应该是可以理解的,无论您的背景如何)。请注意,它a是来自A(最初是根)b的节点,并且是来自B(最初是在步骤 1 中找到的节点)的节点
function checkTrees(node a, node b) returns boolean
if a does not exist or b does not exist then
// base of the recursion
return false
else if a is different from b then
// compare the current nodes
return false
else
// check the children of a
boolean leftFound = true
boolean rightFound = true
if a.left exists then
// try to match the left child of a with
// every possible neighbor of b
leftFound = checkTrees(a.left, b.left)
or checkTrees(a.left, b.right)
or checkTrees(a.left, b.parent)
if a.right exists then
// try to match the right child of a with
// every possible neighbor of b
leftFound = checkTrees(a.right, b.left)
or checkTrees(a.right, b.right)
or checkTrees(a.right, b.parent)
return leftFound and rightFound
关于运行时间:设m为 中的节点数,A为n中的节点数B。第一步的搜索需要O(n)时间。第二步的运行时间取决于我所做的一个关键假设,但这可能是错误的:我假设 的每个节点最多A等于的一个节点。如果是这样的话,第二步的运行时间是(因为你永远不可能在错误的方向上搜索太远)。所以总运行时间为.BO(m)O(m + n)
在写下我的假设时,我开始怀疑这是否过于简单化了你的情况......