Leetcode 572. Subtree of Another Tree
You are given the roots of two binary trees root and subRoot. Write a function to determine if subRoot is a subtree of root.
A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node’s descendants. The tree tree could also be considered as a subtree of itself.
Example 1:
Input: root = [3,4,5,1,2], subRoot = [4,1,2]
Output: true
Example 2:
Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
Output: false
subRoot is empty, it is trivially a subtree of any tree. If root is empty and subRoot is not, it is trivially false.true if subRoot is a subtree of root, otherwise false.root tree and, at each node, checking if the subtree rooted at this node matches subRoot.root tree and use isSameTree to check for subtree matches.root tree using recursion.isSameTree to check if the subtree rooted at this node matches subRoot.true.false.#include <iostream>
// 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) {
if (!root) return !subRoot;
if (isSameTree(root, subRoot)) return true;
return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);
}
bool isSameTree(TreeNode* s, TreeNode* t) {
if (!s && !t) return true;
if (!s || !t) return false;
if (s->val != t->val) return false;
return isSameTree(s->left, t->left) && isSameTree(s->right, t->right);
}
};
int main() {
// Example usage:
TreeNode* root = new TreeNode(3);
root->left = new TreeNode(4);
root->right = new TreeNode(5);
root->left->left = new TreeNode(1);
root->left->right = new TreeNode(2);
TreeNode* subRoot = new TreeNode(4);
subRoot->left = new TreeNode(1);
subRoot->right = new TreeNode(2);
Solution sol;
std::cout << (sol.isSubtree(root, subRoot) ? "true" : "false") << std::endl; // Output: true
// Clean up
delete root->left->left;
delete root->left->right;
delete root->left;
delete root->right;
delete root;
delete subRoot->left;
delete subRoot->right;
delete subRoot;
return 0;
}
root tree and N is the number of nodes in the subRoot tree.
isSameTree is called M times, and each call to isSameTree is O(N).This strategy ensures that we efficiently traverse and compare subtrees to determine if subRoot is a subtree of root.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?