LeetCode 572: Subtree of Another Tree
Problem Description
Explanation
To solve this problem, we can recursively traverse the main tree and check if at any node, a subtree exists that is identical to the given subRoot tree. We can do this by comparing the trees starting from the current node. We can break down the problem into smaller sub-problems by recursively checking if the left or right subtree of the current node is equal to the subRoot tree.
Time complexity: O(m*n) where m is the number of nodes in the main tree and n is the number of nodes in the subRoot tree.
Space complexity: O(min(m,n))
Solutions
class Solution {
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
if (root == null) return false;
return isSameTree(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
}
private boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) return true;
if (p == null || q == null) return false;
return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
Related LeetCode Problems
Loading editor...