Skip to content

Commit

Permalink
re-solve "100. Same Tree"
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Nov 3, 2024
1 parent f3adec9 commit ccd4716
Showing 1 changed file with 8 additions and 25 deletions.
33 changes: 8 additions & 25 deletions src/same_tree.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,13 @@
from typing import TypeAlias

from src.utils.binary_tree import TreeNode

Stack: TypeAlias = list[TreeNode | None]


class Solution:
def isSameTree(self, p: TreeNode | None, q: TreeNode | None) -> bool:
stack_p: Stack = [p]
stack_q: Stack = [q]

while stack_p and stack_q:
node_p = stack_p.pop()
node_q = stack_q.pop()

if node_p and node_q:
if node_p.val != node_q.val:
return False

stack_p.append(node_p.left)
stack_p.append(node_p.right)
stack_q.append(node_q.left)
stack_q.append(node_q.right)
elif node_p is None and node_q is None:
continue
else:
return False

return not stack_p and not stack_q
if not p and not q:
return True
elif not p or not q or p.val != q.val:
return False
else:
return self.isSameTree(p.left, q.left) and self.isSameTree(
p.right, q.right
)

0 comments on commit ccd4716

Please sign in to comment.