C++ Recursive Solution


  • 0
    H

    checkSubtree function checks two trees to see if they match

    isSubtree function runs through each node from tree s and uses it as root to compare it with tree t

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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.