Subtree Of Another Tree Problem
Description
LeetCode Problem 572.
Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise.
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
Constraints:
- The number of nodes in the root tree is in the range [1, 2000].
- The number of nodes in the subRoot tree is in the range [1, 1000].
- -10^4 <= root.val <= 10^4
- -10^4 <= subRoot.val <= 10^4
Solution
Approach: Compare at Every Node
subRoot is a subtree of root exactly when some node of root, together with everything below it, is identical to subRoot. So try every node of root as the starting point and check whether the two trees match from there.
Two helpers, both recursive:
isSameTree(a, b): two trees are identical if both are empty, or both exist, have the same value, and their left subtrees and right subtrees are identical.isSubtree(root, subRoot): returnfalsefor an emptyroot. Otherwise, returntrueifisSameTree(root, subRoot), or ifsubRootis a subtree ofroot.leftor ofroot.right.
The detail people get wrong is matching only the top part: a subtree must include all descendants of its node. In Example 2 the node 4 has values 4, 1, 2 on top, but 1 has an extra child 0, so isSameTree fails when it reaches 0 against a missing node and the answer is false.
Complexity: O(m · n) time in the worst case, where m and n are the numbers of nodes in root and subRoot, since each node of root may start a comparison of up to n nodes. O(h) space for the recursion, where h is the height of root.
class Solution:
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
if root is None:
return False
# Either the tree rooted here equals subRoot, or subRoot is inside one of the children.
return (self.isSameTree(root, subRoot)
or self.isSubtree(root.left, subRoot)
or self.isSubtree(root.right, subRoot))
def isSameTree(self, a: Optional[TreeNode], b: Optional[TreeNode]) -> bool:
if a is None or b is None:
return a is b # equal only if both are missing
return (a.val == b.val
and self.isSameTree(a.left, b.left)
and self.isSameTree(a.right, b.right))
Now write it from memory
Close the write-up and solve it yourself against the tests.