C++ convert to vector and search

  • 0

    Covert the trees to vector in preorder, and check if the first vector contains the second vector.
    This solution is assuming INT_MAX is not in the tree. Should be modified if the condition would not match anymore.

        bool isSubtree(TreeNode* s, TreeNode* t) {
            vector<int> v1, v2;
            tree_to_str(s, v1);
            tree_to_str(t, v2);
            return std::search(v1.begin(), v1.end(), v2.begin(), v2.end()) != v1.end();
        void tree_to_str(TreeNode* s, std::vector<int>& v) {
            if (s) {
                tree_to_str(s->left, v);
                tree_to_str(s->right, v);
            } else {

Log in to reply

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