C++ straight-forward solution

  • 0
        int flag=0;
        bool isSubtree(TreeNode* s, TreeNode* t) {
            if(s==NULL&&t==NULL) return true;
            if(s==NULL||t==NULL) return false;
            DFS(t, s);
            return flag==1;
        void DFS(TreeNode* r, TreeNode* s) {
            if(flag==1||s==NULL) return;
            if(s->val==r->val) {
                if(check(s, r)) flag=1;
            DFS(r, s->left);
            DFS(r, s->right);
        bool check(TreeNode* big, TreeNode* small) {
            if(big==NULL&&small==NULL) return true;
            if((big!=NULL&&small==NULL)||(big==NULL&&small!=NULL)||(big->val!=small->val)) return false;
            return check(big->left, small->left)&&check(big->right, small->right);

Log in to reply

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