#include"iostream" #include"stdio.h" #include"math.h" using namespace std; struct BinaryTreeNode { double m_Value; BinaryTreeNode* m_pLeft; BinaryTreeNode* m_pRight; }; BinaryTreeNode* CreateBinaryTreeNode(double value) { BinaryTreeNode* pNode=new BinaryTreeNode(); pNode->m_Value=value; pNode->m_pLeft=nullptr; pNode->m_pRight=nullptr; return pNode; } void ConnectTreeNodes(BinaryTreeNode* pParent,BinaryTreeNode* pLeft,BinaryTreeNode* pRight) { if(pParent!=nullptr) { pParent->m_pLeft=pLeft; pParent->m_pRight=pRight; } } void PrintTreeNode(const BinaryTreeNode* pNode) { if(pNode!=nullptr) { cout<<"value of this node is:"<<pNode->m_Value<<endl; if(pNode->m_pLeft!=nullptr) cout<<"value of its left child is:"<<pNode->m_pLeft->m_Value<<endl; else cout<<"left child is nullptr."<<endl; if(pNode->m_pRight!=nullptr) cout<<"value of its right child is:"<<pNode->m_pRight->m_Value<<endl; else cout<<"right child is nullptr."<<endl; } else cout<<"this node is nullptr."<<endl; cout<<endl; } void PrintTree(const BinaryTreeNode* pRoot) { PrintTreeNode(pRoot); if(pRoot!=nullptr) { if(pRoot->m_pLeft!=nullptr) PrintTreeNode(pRoot->m_pLeft); if(pRoot->m_pRight!=nullptr) PrintTreeNode(pRoot->m_pRight); } } void DestroyTree(BinaryTreeNode* pRoot) { if(pRoot!=nullptr) { BinaryTreeNode* pLeft=pRoot->m_pLeft; BinaryTreeNode* pRight=pRoot->m_pRight; delete pRoot; pRoot=nullptr; DestroyTree(pLeft); DestroyTree(pRight); } } bool Equal(const double &a,const double &b) { if(fabs(a-b)<0.0000001) return true; return false; } bool DoesTreeAHaveTreeB(BinaryTreeNode* pRootA,BinaryTreeNode* pRootB) { if(pRootB==nullptr) return true; if(pRootA==nullptr) return false; if(Equal(pRootA->m_Value,pRootB->m_Value)) { return DoesTreeAHaveTreeB(pRootA->m_pLeft,pRootB->m_pLeft)&&DoesTreeAHaveTreeB(pRootA->m_pRight,pRootB->m_pRight); } else { return false; } } bool HasSubTree(BinaryTreeNode* pRootA,BinaryTreeNode* pRootB) { if(pRootB==nullptr) return false; if(pRootA==nullptr) return false; bool result=false; if(Equal(pRootA->m_Value,pRootB->m_Value)) { result=DoesTreeAHaveTreeB(pRootA,pRootB); } if(!result) { result=HasSubTree(pRootA->m_pLeft,pRootB); } if(!result) { result=HasSubTree(pRootA->m_pRight,pRootB); } return result; }