C++ Solution using same_tree() as a subroutine (Beats 90% of submissions)


  • 0
    B

    This isn't the most efficient solution, but it was surprisingly fast compared to many others.

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

Log in to reply
 

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