Same Tree

Problem Statement:

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.

Example:

Pasted image 20260210184349.png

Input: p = [1,2,3], q = [1,2,3]
Output: true

Intuition:

Pretty straight forward, check start checking for every node it is same if not return false.


Code:

My Solution

def isSameTree(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


#binary-tree #dsa