树的子结构

 

 

c++

 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 result = false;
15         if(pRoot1 && pRoot2){
16             if(pRoot1->val == pRoot2->val){
17                 result=panduan(pRoot1,pRoot2);
18             }
19             if(!result){
20                 result = panduan(pRoot1->left,pRoot2);
21             }
22             if(!result){
23                 result=panduan(pRoot1->right,pRoot2);
24             }
25         }
26         return result;
27     }
28     //判断两个node是否相同
29     bool panduan(TreeNode* node1, TreeNode* node2){
30         //node2遍历完了,node1还没完或者node1正好也完了
31         if(!node2) return true;
32         //node1遍历完,node2还没完
33         if(!node1) return false;
34         if(node1->val != node2->val) return false;
35         return panduan(node1->left,node2->left) && panduan(node1->right,node2->right);
36     }
37 };

 

posted @ 2019-07-06 13:34  Austin_anheqiao  阅读(155)  评论(0编辑  收藏  举报