LeetCode T572.SubTree of Another Tree/另一棵树的子树

 

 这是一道简单的子树匹配问题,可以直接用深度优先搜索来完成,递归地比较每一个子树是否与给定子树匹配就可以了。

我的题解代码如下,他LeetCode不给过,我觉得逻辑上没什么问题。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
bool check(struct TreeNode *o,struct TreeNode *t){
    if(!o && !t) return true;
    if((!o && t) || (o && !t) || (o->val!=t->val)) return false;
    return check(o->left,t->left) && check(o->right,t->right);
}

bool DFS(struct TreeNode *o,struct TreeNode *t){
    if(!o) return false;
    return check(o,t) || check(o->left,t) || check(o->right,t);
}

bool isSubtree(struct TreeNode* s, struct TreeNode* t){
    return DFS(s,t);
}

 

posted @ 2020-05-07 08:36  runsdeep  阅读(157)  评论(0编辑  收藏  举报