Skip to content

Commit a002894

Browse files
committed
solve: sameTree
1 parent cf5691a commit a002894

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

same-tree/yolophg.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Time Complexity: O(N) - visit each node once.
2+
# Space Complexity: O(N) in the worst case (skewed tree), O(log N) in the best case (balanced tree).
3+
4+
class Solution:
5+
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
6+
# if both trees are empty, they are obviously the same
7+
if p is None and q is None:
8+
return True
9+
10+
# if one tree is empty but the other is not, they can't be the same
11+
if p is None or q is None:
12+
return False
13+
14+
# if values of the current nodes are different, trees are not the same
15+
if p.val != q.val:
16+
return False
17+
18+
# recursively check both left and right subtrees
19+
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

0 commit comments

Comments
 (0)