Given the roots of two binary trees p and q, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
Input: p = [1,2,3], q = [1,2,3]
Output: true
Input: p = [1,2], q = [1,null,2]
Output: false
Input: p = [1,2,1], q = [1,1,2]
Output: false
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
queue=[]
queue.append((p,q))
while queue:
p1,q1=queue.pop(0)
if not p1 and not q1:
continue
elif None in [p1,q1]:
return False
else:
if p1.val!=q1.val:
return False
queue.append((p1.left,q1.left))
queue.append((p1.right,q1.right))
return True
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
stack=[]
stack.append((p,q))
while stack:
p1,q1=stack.pop()
if not p1 and not q1:
continue
elif None in [p1,q1]:
return False
else:
if p1.val!=q1.val:
return False
stack.append((p1.right,q1.right))
stack.append((p1.left,q1.left))
return True
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if not p and not q:
return True
if p and q and p.val==q.val:
return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
return False
if None in [p1,q1]:
pop(0)
) or the rightmost(pop()
) element.(1) DFS
stack.pop()
...
stack.append((p1.right, q1.right))
stack.append((p1.left, q1.right))
(2) BFS
queue.pop(0)
...
queue.append((p1.left, q1.right))
queue.append((p1.right, q1.right))
References
https://leetcode.com/problems/same-tree/
https://leetcode.com/problems/same-tree/discuss/32894/Python-Recursive-solution-and-DFS-Iterative-solution-with-stack-and-BFS-Iterative-solution-with-queue