题目描述
输入两颗二叉树A,B,判断B是不是A的子结构。
1 /* 2 struct TreeNode { 3 int val; 4 struct TreeNode *left; 5 struct TreeNode *right; 6 TreeNode(int x) : 7 val(x), left(NULL), right(NULL) { 8 } 9 };*/ 10 class Solution { 11 public: 12 bool DFS(TreeNode* pRoot1, TreeNode* pRoot2) 13 { 14 if ( pRoot1->val != pRoot2->val) 15 return 0; 16 bool b1,b2; 17 if (pRoot1->left != NULL && pRoot2->left != NULL) 18 { 19 b1 = DFS(pRoot1->left,pRoot2->left); 20 } 21 else if (pRoot2->left == NULL) 22 { 23 b1 = 1; 24 } 25 else 26 { 27 b1 = 0; 28 } 29 30 if (pRoot1->right != NULL && pRoot2->right != NULL) 31 { 32 b2 = DFS(pRoot1->right,pRoot2->right); 33 } 34 else if (pRoot2->right == NULL) 35 { 36 b2 = 1; 37 } 38 else 39 { 40 b2 = 0; 41 } 42 43 return b1 && b2; 44 } 45 bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) 46 { 47 if (pRoot1 == NULL || pRoot2 == NULL) 48 return 0; 49 std::queue<TreeNode*> qq; 50 qq.push(pRoot1); 51 bool is = 0; 52 while(!qq.empty()) 53 { 54 TreeNode* tem = qq.front(); 55 qq.pop(); 56 if(is = DFS(tem,pRoot2)) 57 return 1; 58 if (tem->left != NULL) 59 qq.push(tem->left); 60 if (tem->right != NULL) 61 qq.push(tem->right); 62 } 63 return 0; 64 } 65 };