Leetcode: Subtree of Another Tree
Your code doesn't look that ugly!  Here are some suggestions to make it better.  Note that LeetCode makes significantly more mistakes than you when it comes to code quality; I have listed the suggestions for LeetCode-provided stuff too, so that you don't make the same mistakes when you are writing real code &mdash; you don't have to force LeetCode to accept them (i.e., some of them can be compromised for the purpose of passing their tests).

General design

The Solution class is very Java-style AFAIK, but it is not idiomatic in C++.  It should be replaced by a namespace, or removed altogether.  In C++, it is preferred to create a separate Tree class for the binary trees, instead of operating directly on the nodes.  Also, the value type should be a template parameter for reusability.

Naming

In C++, functions and variables are generally named in snake_case, with CamelCase names reserved for classes.

The name of the function is misleading &mdash; to me, isSubtree(s, t) means "s is a subtree of t," rather than the reverse.  contains_subtree may be better.  The parameters s and t are also non-descriptive and thus unreadable; I recommend tree and subtree.

The parameters to isSame (or maybe just same), on the other hand, can be named as simply as tree_a and tree_b, because the semantics is unambiguous.

Logic

(Note: the code snippets presented are intended to help you understand the review.  They are not tested; in other words, they and may contain mistakes and are not guaranteed to work.)

The logic of same can be simplified:


if both arguments are non-null, then they are identical if and only if


their values are equal; and
their left subtrees are identical; and
their right subtrees are identical;

otherwise, they are identical if and only if they are both null.




bool same(TreeNode* tree_a, TreeNode* tree_b)
{
    if (tree_a &amp;&amp; tree_b) {
        return tree_a-&gt;val == tree_b-&gt;val
            &amp;&amp; same(tree_a-&gt;left, tree_b-&gt;left)
            &amp;&amp; same(tree_a-&gt;right, tree_b-&gt;right);
    } else {
        return !tree_a &amp;&amp; !tree_b;
    }
}


This presents your logic in a way that is (hopefully) more readable.

Similarly,


if tree is non-null, then tree contains subtree if and only if


same(tree, subtree); or
tree-&gt;left contains subtree; or
tree-&gt;right contains subtree;

otherwise, tree contains subtree if and only if subtree is null as well.




bool contains_subtree(TreeNode* tree, TreeNode* subtree)
{
    if (tree) {
        return same(tree, subtree)
            || contains_subtree(tree-&gt;left, subtree)
            || contains_subtree(tree-&gt;right, subtree);
    } else {
        return !subtree;
    }
}


This refactoring eliminates the unnatural non-local control flow (i.e., writing to the bool&amp; argument instead of using the return value).  It also ensures that the function returns as soon as a match is found.