-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path572_Subtree_of_Another_Tree.py
More file actions
32 lines (26 loc) · 938 Bytes
/
Copy path572_Subtree_of_Another_Tree.py
File metadata and controls
32 lines (26 loc) · 938 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
if root is None:
return False
if self.isSameTree(root, subRoot):
return True
return (self.isSubtree(root.left, subRoot) or
self.isSubtree(root.right, subRoot))
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if p == None:
return q == None
if q == None:
return p == None
if p.val != q.val:
return False
if self.isSameTree(p.left, q.left) == False:
return False
if self.isSameTree(p.right, q.right) == False:
return False
return True