例如:- 请参阅随附的二叉树示例 T1 和 T2。
请注意,此问题与子树问题不同。binaryTree T2 包含在二叉树 T1 中,如果 T2 在 T1 中存在结构上完全相同的布局,并且 T1 可能包含额外的结构 [这无关紧要]。
我已经用下面的代码解决了这个问题。它有点太复杂了,无法解释,但请通过调试理解它。您调用函数的方式在下面的这一行。这里 tree1 是 T1 , tree2 是 T2 , size2 是 T2 树的大小。
return(containsInternal(tree1.getRoot(), tree2.getRoot(), size2));
// This function checks if the node1 is contained with in another binary tree with starting point of node2 [ which means node1->m_data==node2->m_data has been verified ].
// This is not same as subtree problem. Read the code carefully.
bool checkContains(const BinaryTreeNode<int>* node1, const BinaryTreeNode<int>* node2, long& iterations)
{
if(iterations<0)
return(true);
if(!node1)
return(true);
bool returnStatus1=true, returnStatus2=false, returnStatus3=true;
if(node1->m_leftChild)
{
if(!node2->m_leftChild)
return(false);
else
returnStatus1=checkContains(node1->m_leftChild, node2->m_leftChild, iterations);
}
//cout<<"Attempting to compare "<<node1->m_data<<" and "<<node2->m_data<<" with iterations left = "<<iterations<<endl;
if(node1->m_data==node2->m_data)
{
returnStatus2=true;
--iterations;
}
if(node1->m_rightChild)
{
if(!node2->m_rightChild)
return(false);
else
returnStatus3=checkContains(node1->m_rightChild, node2->m_rightChild, iterations);
}
return(returnStatus1&&returnStatus2&&returnStatus3);
}
// Iterate tree starting at node1 in in order traversal and if node matches node of tree2 then start doing contains checking further.
bool containsInternal(const BinaryTreeNode<int>* node1, const BinaryTreeNode<int>* node2, long size)
{
if(!node1||!node2)
return(false);
bool result1=containsInternal(node1->m_leftChild, node2, size);
bool result2=false;
if(node1->m_data==node2->m_data)
result2=checkContains(node2, node1, size); // Note : node2 is passed first argument since checkContains traverses structure of BT of first argument.size is size of tree of node2.
bool result3=containsInternal(node1->m_rightChild, node2, size);
return(result1||result2||result3);
}
// Checks if the tree2 is a part of the tree1.
bool contains(BinaryTree<int>& tree1, BinaryTree<int>& tree2)
{
size_t size1=tree1.size();
size_t size2=tree2.size();
if(!size2)
return(true); // null tree is always contained in another tree.
if(size2>size1)
return(false); // The tree2 can not be inside tree1 if it is bigger in size.
return(containsInternal(tree1.getRoot(), tree2.getRoot(), size2));
}