树的子结构
输入两颗二叉树A,B,判断B是不是A的子结构。
遍历A,然后用A的每个节点与B进行判断
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 HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) 13 { 14 bool res=false; 15 if(pRoot1!=NULL&&pRoot2!=NULL){ 16 if(pRoot1->val==pRoot2->val) 17 res=isSubtree(pRoot1,pRoot2); 18 if(!res) 19 res=HasSubtree(pRoot1->left,pRoot2); 20 if(!res) 21 res=HasSubtree(pRoot1->right,pRoot2); 22 } 23 return res; 24 } 25 private: 26 bool isSubtree(TreeNode* pRoot1, TreeNode* pRoot2){ 27 if(pRoot2==NULL) return true; 28 if(pRoot1==NULL) return false; 29 if(pRoot1->val==pRoot2->val) 30 return isSubtree(pRoot1->left,pRoot2->left)&&isSubtree(pRoot1->right,pRoot2->right); 31 return false; 32 } 33 };
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=