Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node’s descendants. The tree s could also be considered as a subtree of itself.
Example 1:
Given tree s:
3
/ \
4 5
/ \
1 2
Given tree t:
4
/ \
1 2
Return true, because t has the same structure and node values with a subtree of s.
Example 2:
Given tree s:
3
/ \
4 5
/ \
1 2
/
0
Given tree t:
4
/ \
1 2
Return false.
Here, each node in tree s regarded as root node and is compared with t. Iteration and Recursion methods are used to solve this problem.
- Recursion
class Solution:
def isSubtree(self, s: 'TreeNode', t: 'TreeNode') -> 'bool':
# Recursive
def issubtree(node1, node2):
if not node1 or not node2:
if (not node1 and node2) or (node1 and not node2):
return False
return True
if node1.val == node2.val:
return issubtree(node1.left, node2.left) & issubtree(node1.right, node2.right)
else:
return False
if s is None or t is None:
if (not s and t) or (s and not t):
return False
return True
if issubtree(s, t):
return True
return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
- Iteration
class Solution:
def isSubtree(self, s: 'TreeNode', t: 'TreeNode') -> 'bool':
# Iteration
def issubtree(node1, node2):
if not node1 or not node2:
if (not node1 and node2) or (node1 and not node2):
return False
return True
if node1.val == node2.val:
return issubtree(node1.left, node2.left) & issubtree(node1.right, node2.right)
else:
return False
if not s:
return False
stack = [s]
while stack:
node = stack.pop() # node = stack.pop(0)
if issubtree(node, t):
return True
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return False