树的子结构

  题目:输入两颗二叉树A和B,判断B是不是A的子结构。二叉树的定义如下:

struct TreeNode{
    int val;
    TreeNode* left;
    TreeNode* right;
};

    代码如下:

 1  bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
 2     {
 3         bool result = false;
 4         if(pRoot1!=NULL&&pRoot2!=NULL){
 5             if(pRoot1->val == pRoot2->val)
 6                 result = DoesTree1HaveTree2(pRoot1,pRoot2);
 7             if(!result)
 8                 result = HasSubtree(pRoot1->left,pRoot2);
 9             if(!result)
10                 result = HasSubtree(pRoot1->right,pRoot2);
11         }
12         return result;
13 
14     }
15     
16     bool DoesTree1HaveTree2(TreeNode* pRoot1,TreeNode* pRoot2){
17         if(pRoot2==NULL)
18             return true;
19         if(pRoot1==NULL)
20             return false;
21         if(pRoot1->val != pRoot2->val)
22             return false;
23         return DoesTree1HaveTree2(pRoot1->left,pRoot2->left)&&DoesTree1HaveTree2(pRoot1->right,pRoot2->right);
24     }

 

posted @ 2016-08-18 12:45  没长大的书生  阅读(136)  评论(0编辑  收藏  举报