LeetCode 100. Same Tree

November 20, 2024

Today I chose an easy problem since I had a late day at work and gym afterwards.

Solution

1from collections import deque
2
3# Definition for a binary tree node.
4# class TreeNode:
5# def __init__(self, val=0, left=None, right=None):
6# self.val = val
7# self.left = left
8# self.right = right
9class Solution:
10 def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
11 pQ = deque([p])
12 qQ = deque([q])
13
14 while pQ and qQ:
15 nodeP = pQ.popleft()
16 nodeQ = qQ.popleft()
17 if nodeP and nodeQ and nodeP.val != nodeQ.val:
18 return False
19 elif (nodeP is None) != (nodeQ is None):
20 return False
21
22 if nodeP:
23 pQ.append(nodeP.left)
24 pQ.append(nodeP.right)
25 if nodeQ:
26 qQ.append(nodeQ.left)
27 qQ.append(nodeQ.right)
28
29 if not pQ and not qQ:
30 return True
31
32 return False

Time complexity is O(n) = n and space complexity is O(n).

LeetCode 25. Reverse Nodes in k-Group

LeetCode 82. Remove Duplicates from Sorted List II