<p>Given the roots of two binary trees <code>root</code> and <code>subRoot</code>, return <code>true</code> if there is a subtree of <code>root</code> with the same structure and node values of<code> subRoot</code> and <code>false</code> otherwise.</p>

<p>A subtree of a binary tree <code>tree</code> is a tree that consists of a node in <code>tree</code> and all of this node&#39;s descendants. The tree <code>tree</code> could also be considered as a subtree of itself.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/04/28/subtree1-tree.jpg" style="width: 532px; height: 400px;" />
<pre>
<strong>Input:</strong> root = [3,4,5,1,2], subRoot = [4,1,2]
<strong>Output:</strong> true
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/04/28/subtree2-tree.jpg" style="width: 502px; height: 458px;" />
<pre>
<strong>Input:</strong> root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
<strong>Output:</strong> false
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li>The number of nodes in the <code>root</code> tree is in the range <code>[1, 2000]</code>.</li>
	<li>The number of nodes in the <code>subRoot</code> tree is in the range <code>[1, 1000]</code>.</li>
	<li><code>-10<sup>4</sup> &lt;= root.val &lt;= 10<sup>4</sup></code></li>
	<li><code>-10<sup>4</sup> &lt;= subRoot.val &lt;= 10<sup>4</sup></code></li>
</ul>

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isSubtree(TreeNode* root, TreeNode* subRoot) {
        vector<int> v1, v2, w1, w2;
        dfs(root, v1, w1);
        dfs(subRoot, v2, w2);

        for (const int el : v1) std::cout << el << " ";
        std::cout << std::endl;

        for (const int el : v2) std::cout << el << " ";
        std::cout << std::endl;

        for (int i = 0; i < v1.size(); ++ i) {
            bool found = true;
            for (int j = 0; j < v2.size(); ++ j)
                if (v1[i + j] != v2[j]) {
                    found = false;
                    break;
                }
            if (found && w1[i] == w2[0]) return true;
        }
        return false;
    }

    int dfs(TreeNode* root, vector<int>& v, vector<int>& w) {
        v.push_back(root->val);
        w.push_back(1);
        const int ws = w.size();
        if (root->left) w[ws - 1] += dfs(root->left, v, w);
        else { v.push_back(-1); w.push_back(1); }
        if (root->right) w[ws - 1] += dfs(root->right, v, w);
        else { v.push_back(-1); w.push_back(1); }
        return w[ws - 1];
    }
};
30600