题目:输入两棵二叉树A和B,判断B是不是A的子结构。
思路:在二叉树A中遍历寻找B的根节点,如果找到,则继续比较左右子树结点。
测试用例:
1.功能测试:B是或不是A的子结构 2.特殊测试:NULL#include#include using namespace std;struct BinaryTreeNode{ int m_nValue; BinaryTreeNode* m_pLeft; BinaryTreeNode* m_pRight;};//创建树结点BinaryTreeNode* CreateNode(int value){ BinaryTreeNode* TreeNode = new BinaryTreeNode(); TreeNode->m_nValue = value; TreeNode->m_pLeft = NULL; TreeNode->m_pRight = NULL; return TreeNode;}//连接树结点void ConnectTreeNodes(BinaryTreeNode* pRoot, BinaryTreeNode* pLeft, BinaryTreeNode* pRight){ if (pRoot == NULL) { return; } pRoot->m_pLeft = pLeft; pRoot->m_pRight = pRight;}//销毁树void DestroyTree(BinaryTreeNode* pRoot){ if (pRoot != NULL) { delete pRoot; pRoot = NULL; DestroyTree(pRoot->m_pLeft); DestroyTree(pRoot->m_pRight); }}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);}bool HasSubtree(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2){ bool result = false; if (pRoot1 != NULL && pRoot2 != NULL) { 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;}void test1(){ BinaryTreeNode* node1 = CreateNode(8); BinaryTreeNode* node2 = CreateNode(8); BinaryTreeNode* node3 = CreateNode(7); BinaryTreeNode* node4 = CreateNode(9); BinaryTreeNode* node5 = CreateNode(2); ConnectTreeNodes(node1, node2, node3); ConnectTreeNodes(node2, node4, node5); BinaryTreeNode* node6 = CreateNode(8); BinaryTreeNode* node7 = CreateNode(9); BinaryTreeNode* node8 = CreateNode(2); ConnectTreeNodes(node6, node7, node8); bool result = HasSubtree(node1, node6); if (result) { cout << "成功!" << endl; }}int main(){ test1(); return 0;}