1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 11 static int wing=[]() 12 { 13 std::ios::sync_with_stdio(false); 14 cin.tie(NULL); 15 return 0; 16 }(); 17 18 class Solution 19 { 20 public: 21 22 vector<TreeNode*> vt; 23 bool isSubtree(TreeNode* s, TreeNode* t) 24 { 25 if(t==NULL) 26 return true; 27 if(s==NULL&&t!=NULL) 28 return false; 29 findnode(s,t->val); 30 for(TreeNode* pr:vt) 31 { 32 if(judgesame(pr,t)) 33 return true; 34 } 35 return false; 36 } 37 38 void findnode(TreeNode *root,int k) 39 { 40 queue<TreeNode*> q; 41 TreeNode* p=root; 42 q.push(p); 43 while(!q.empty()) 44 { 45 p=q.front(); 46 if(p->val==k) 47 vt.push_back(p); 48 if(p->left!=NULL) 49 q.push(p->left); 50 if(p->right!=NULL) 51 q.push(p->right); 52 q.pop(); 53 } 54 } 55 56 bool judgesame(TreeNode* a,TreeNode* b) 57 { 58 if(a==NULL&&b==NULL) 59 return true; 60 if(a==NULL||b==NULL) 61 return false; 62 if(a->val!=b->val) 63 return false; 64 return judgesame(a->left,b->left)&&judgesame(a->right,b->right); 65 } 66 };
上面用的迭代+递归的方法,先遍历一次主树,找出和子树根节点值相等的点,这些点即为可能和子树相同主树上的子树,之后在依次判定以这些节点为根节点的子树是否和子树相同。
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 11 static int wing=[]() 12 { 13 std::ios::sync_with_stdio(false); 14 cin.tie(NULL); 15 return 0; 16 }(); 17 18 class Solution 19 { 20 public: 21 22 bool isSubtree(TreeNode* s, TreeNode* t) 23 { 24 return !t || (s && (judgesame(s, t) || isSubtree(s->left, t) || isSubtree(s->right, t))); 25 } 26 27 28 bool judgesame(TreeNode* a,TreeNode* b) 29 { 30 return a==NULL? b==NULL:b&&(a->val==b->val)&&judgesame(a->left,b->left)&&judgesame(a->right,b->right); 31 } 32 };
这个用的递归,可读性不是很强,但是意思很明显,代码很少。
浙公网安备 33010602011771号