572. Subtree of Another Tree
Problem
Decide whether subRoot appears in root as a subtree: some node of root together with all of its descendants is identical to subRoot.
Example: root = [3,4,5,1,2], subRoot = [4,1,2] → true; with an extra 0 under the 2 in root → false
For every node of root, check isSameTree(node, subRoot). (O(m+n) alternative: serialize both and do substring search / hashing.)
Complexity: O(m·n) worst case.
class Solution:
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
def same(a, b):
if not a or not b:
return a is b
return a.val == b.val and same(a.left, b.left) and same(a.right, b.right)
if not root:
return False
return same(root, subRoot) or self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)
assert Solution().isSubtree(make_tree([3, 4, 5, 1, 2]), make_tree([4, 1, 2])) is True
assert Solution().isSubtree(make_tree([3, 4, 5, 1, 2, None, None, None, None, 0]), make_tree([4, 1, 2])) is False
class Solution {
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
if (root == null) return false;
return same(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
}
private boolean same(TreeNode a, TreeNode b) {
if (a == null || b == null) return a == b;
return a.val == b.val && same(a.left, b.left) && same(a.right, b.right);
}
}
func isSubtree(root *TreeNode, subRoot *TreeNode) bool {
if root == nil {
return false
}
return same(root, subRoot) || isSubtree(root.Left, subRoot) || isSubtree(root.Right, subRoot)
}
func same(a, b *TreeNode) bool {
if a == nil || b == nil {
return a == b
}
return a.Val == b.Val && same(a.Left, b.Left) && same(a.Right, b.Right)
}