struct BinaryTreeNode{ int m_nValue; BinaryTreeNode *m_pLeft; BinaryTreeNode *m_pRight; };
//在数A中查找与树B根结点值相同的结点,然后递归判断,查找过程也是递归 bool HasSubTree(BinaryTreeNode *pRoot1, BinaryTreeNode *pRoot2) { bool result=false; if (pRoot1->m_nValue==pRoot2->m_nValue) { result=DoesTree1HaveTree2(pRoot1,pRoot2); if (!result) { result=HasSubTree(pRoot1->m_pLeft,pRoot2); } if (!result) { result=HasSubTree(pRoot1->m_pRight,pRoot2); } } return result; } //判断树A的子树是不是和树B有相同的结构 bool DoesTree1HaveTree2(BinaryTreeNode *pRoot1, BinaryTreeNode *pRoot2) { if (pRoot2==NULL) { return true; } if (pRoot1==NULL) { return false; } if (pRoot1->m_nValue!=pRoot2->m_nValue) { return false; } return DoesTree1HaveTree2(pRoot1->m_pLeft,pRoot2->m_pLeft)&&DoesTree1HaveTree2(pRoot1->m_pRight, pRoot2->m_pRight); }
原文:http://blog.csdn.net/lsh_2013/article/details/45750537