So, the idea here is that if we have ~p and ~q at the same time, that's correct.
Otherwise, we return false.
And, if any values don't match as we recursively iterate --> we also return false.
Hopefully this presents what's going on in an easy to understand way.
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ # base cases if not p and not q: return True elif not p: return False elif not q: return False # recursive case return p.val == q.val and \ self.isSameTree(p.left, q.left) and \ self.isSameTree(p.right, q.right)