Analyzing a prove safety tree is not offer another tree substructure

Two binary inputs A, B, B is judged not substructure A's. (Ps: we agreed empty tree is not a tree any substructure)

 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         if(!pRoot1||!pRoot2)
15             return false;
16         bool ans = false;
17         if(pRoot1->val == pRoot2->val)ans = is_subTree(pRoot1,pRoot2);
18         if(!ans) ans = HasSubtree(pRoot1->left,pRoot2);
19         if(!ans) ans = HasSubtree(pRoot1->right,pRoot2);
20         return ans;
21     }
22     bool is_subTree(TreeNode* pRoot1, TreeNode* pRoot2){
23         if(!pRoot2)return true;
24         if(!pRoot1)return false;
25         bool ans = true;
26         if(pRoot1->val != pRoot2->val)ans = false;
27         if(ans) ans = is_subTree(pRoot1->left,pRoot2->left);
28         if(ans) ans = is_subTree(pRoot1->right,pRoot2->right);
29         return ans;
30     }
31 };

 

Guess you like

Origin www.cnblogs.com/--lr/p/11361512.html