Leetcode: Same Tree
Given two binary trees, p
and q
, return True
if they are the same, that is, if all values are the same and False
otherwise.
The easiest solution I could come up with is to use recursion. A few edge cases need to be handled.
Left or right can be null
at any time. In this case it’s clear that the tree cannot be the same. If both nodes are null, the trees are the same.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if p is None and q is None:
return True
if p is None and q is not None:
return False
if q is None and p is not None:
return False
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
Beats 87.04% of users with Python3. Beats 87.04% of users with Python3