/* 题目:二叉树的结点定义如下: struct TreeNode { int m_nValue; TreeNode* m_pLeft; TreeNode* m_pRight; }; 输入两棵二叉树A和B,判断树B是不是A的子结构。 例如,下图中的两棵树A和B,由于A中有一部分子树的结构和B是一样的,因此B就是A的子结构。 1 8 / / / / 8 7 9 2 / / 9 2 / / 4 7 int nodesA[] = {1, 8, 9, -1, -1, 2, 4, -1, -1, 7, -1, -1, 7, -1, -1}; int nodesB[] = {8, 9, -1, -1, 2, -1, -1}; */ // #include "biTree.h" #include <vector> using namespace std; template <typename T> class BinaryTree { public: static BinaryTree<T> *createbintree(); static void pre_order(BinaryTree<T> *t); static char getBiNode(); public: T data; BinaryTree<T> *lchild; BinaryTree<T> *rchild; } ; // Source file #include "stdafx.h" #include "biTree.h" #include <iostream> #include <vector> using namespace std; int pos_exe50 = 0; int IsDentical(BinaryTree<int>* tSubTree,BinaryTree<int>* tChild); BinaryTree<int>* CreateBTreeExe50(int a[]) { BinaryTree<int> *t; int x; //scanf("%c",&x); x= a[pos_exe50++]; if(x==-1) t=NULL; else { t=(BinaryTree<int>*)malloc(sizeof(BinaryTree<int>)); t->data=x; t->lchild=CreateBTreeExe50(a); t->rchild=CreateBTreeExe50(a); } return(t); } bool IsSubTree(BinaryTree<int>* tParent,BinaryTree<int>* tChild) { int isChild = 0; if (tParent == NULL) return isChild; if (tParent->data == tChild->data) { isChild |= IsDentical(tParent, tChild); } else { isChild |= IsSubTree(tParent->lchild, tChild); isChild |= IsSubTree(tParent->rchild, tChild); } return isChild; } int IsDentical(BinaryTree<int>* tSubTree,BinaryTree<int>* tChild) { int ok = 1; if ( tChild == NULL) { ok = 1; } else if (tSubTree->data == tChild->data) { ok &= IsDentical(tSubTree->lchild, tChild->lchild); ok &= IsDentical(tSubTree->rchild, tChild->rchild); } else { ok = 0; } return ok; } void main_exec50() { int nodesA[] = {1, 8, 9, -1, -1, 2, 4, -1, -1, 7, -1, -1, 7, -1, -1}; int nodesB[] = {8, 9, -1, -1, 2, -1, -1}; BinaryTree<int>* tParent = CreateBTreeExe50(nodesA); pos_exe50 = 0; BinaryTree<int>* tChild = CreateBTreeExe50(nodesB); bool ok = IsSubTree(tParent, tChild); cout << "is sub tree: " << ok << endl; }