首页 > 代码库 > [剑指Offer] 17.树的子结构

[剑指Offer] 17.树的子结构

【思路】要查找树A中是否存在和树B结构一样的子树,可以分成两步:

 1.第一步在树A中找到和B的根节点的值一样的结点R;即当前树A包含子树B,HasSubtree(...)

 2.第二步再判断树A中以R为根结点的子树是不是包含和树B一样的结构。即当前树A是否是子树B,IsSubtree(...)

 

 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 IsSubtree(TreeNode* pRoot1, TreeNode* pRoot2){
13         if(pRoot2 == NULL)
14             return true;
15         if(pRoot1 == NULL)
16             return false;
17         if(pRoot1->val == pRoot2->val){
18             return IsSubtree(pRoot1->left, pRoot2->left) && IsSubtree(pRoot1->right, pRoot2->right);
19         }else{
20             return HasSubtree(pRoot1->left, pRoot2) || HasSubtree(pRoot1->right, pRoot2);
21         }
22     }
23    
24     bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2){
25         if(pRoot1 == NULL || pRoot2 == NULL)
26             return false;
27         return IsSubtree(pRoot1,pRoot2) || HasSubtree(pRoot1->left, pRoot2) || HasSubtree(pRoot1->right, pRoot2);
28     }
29 };

 

[剑指Offer] 17.树的子结构