https://leetcode.com/problems/subtree-of-another-tree/description/
Solution 1. Compare s to t, if they are not identical, then compare subtrees of s to t.
bool isIdentical(TreeNode*s, TreeNode* t) {
if(!s && !t) return true;
if(!s || !t) return false;
if(s->val != t->val) return false;
return isIdentical(s->left, t->left) && isIdentical(s->right, t->right);
}
bool isSubtree(TreeNode* s, TreeNode* t) {
if(!t) return true;
if(!s) return false;
if(isIdentical(s, t)) return true;
return isSubtree(s->left, t) || isSubtree(s->right, t);
}
Solution 1.1. Only compare t to the subtrees of s that have same depth as t.
class Solution {
vector<TreeNode*> vd;
public:
int getDepth(TreeNode* s, int d){
if(!s) return 0;
int depth = 1 + max(getDepth(s->left, d), getDepth(s->right, d));
if(depth == d) {
vd.push_back(s);
}
return depth;
}
bool isIdentical(TreeNode*s, TreeNode* t) {
if(!s && !t) return true;
if(!s || !t || s->val != t->val) return false;
return isIdentical(s->left, t->left) && isIdentical(s->right, t->right);
}
bool isSubtree(TreeNode* s, TreeNode* t) {
if(!t) return true;
if(!s) return false;
getDepth(s, getDepth(t, -1));
for(TreeNode* n: vd){
if(isIdentical(n, t)) return true;
}
return false;
}
};
Solution 2. Convert tree to string and compare
void traversal(TreeNode* node, vector<string>& s) {
if(!node) {
s.push_back("#"); return;
}
s.push_back(to_string(node->val));
traversal(node->left, s);
traversal(node->right, s);
}
bool isSub(vector<string>& s, vector<string>& t) {
if(s.size()<t.size()) return false;
for(int i=0; i<s.size();i++){
if(s[i]!=t[0]) continue;
for(int ii=i, j=0; ii<s.size() && j<t.size(); ii++, j++) {
if(s[ii]!=t[j]) break;
if(j==t.size()-1) return true;
}
}
return false;
}
bool isSubtree(TreeNode* s, TreeNode* t) {
if(!t) return true;
if(!s) return false;
vector<string> ss, ts;
traversal(s, ss);
traversal(t, ts);
return isSub(ss, ts);
}
No comments:
Post a Comment