-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathisSubtree.py
More file actions
23 lines (20 loc) · 896 Bytes
/
isSubtree.py
File metadata and controls
23 lines (20 loc) · 896 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 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 not subRoot: return True
def dfs(root):
if not root: return False
if root.val == subRoot.val and isSame(root,subRoot):
return True
return dfs(root.left) or dfs(root.right)
def isSame(root,subRoot):
if not root and not subRoot: return True
if not root and subRoot or root and not subRoot: return False
if root.val != subRoot.val: return False
return isSame(root.left,subRoot.left) and isSame(root.right,subRoot.right)
return dfs(root)