Skip to content

Latest commit

 

History

History
27 lines (22 loc) · 573 Bytes

572SubtreeofAnotherTree.md

File metadata and controls

27 lines (22 loc) · 573 Bytes

##tips:

使用pre-order遍历s,并使用isSame函数来验证t是否是s的子串

class Solution {
public:
    bool isSubtree(TreeNode* s, TreeNode* t) {
        if(!s)
            return false;
        if(isSame(s,t))
            return true;
        return isSubtree(s->left, t)|| isSubtree(s->right,t);
    }

    private:
    bool isSame(TreeNode* s, TreeNode* t){
        if(!s|| !t)
            return s==t;
        if(s->val != t->val)
            return false;
        return isSame(s->left, t->left) && isSame(s->right, t->right);
    }
};