参考leetcode官方
dfs
class Solution {
public:
bool isSubtree(TreeNode* s, TreeNode* t) {
return dfs(s, t);
}
private:
bool dfs(TreeNode* s, TreeNode* t){
if(!s) return false;
return check(s,t) || dfs(s->left, t) || dfs(s->right, t);
}
bool check(TreeNode* s,TreeNode* t){
if( !s&& !t) return true;
if((!s && t)||(s && !t)||(s->val != t->val)) return false;
return check(s->left,t->left) && check(s->right, t->right);
}
};
网友评论