-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path#0100 Same Tree.py
29 lines (25 loc) · 1 KB
/
#0100 Same Tree.py
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
from typing import Optional
# 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 isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
"""
Check if two binary trees are identical.
Args:
p (Optional[TreeNode]): Root node of the first binary tree.
q (Optional[TreeNode]): Root node of the second binary tree.
Returns:
bool: True if the two binary trees are identical, False otherwise.
"""
# Base case: both trees are empty
if not p and not q:
return True
# One tree is empty, the other is not
elif not p or not q:
return False
# Both trees are not empty; compare their values and recursively check left and right subtrees
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)