--- tags: data_structure_python --- # Same Tree <img src="https://img.shields.io/badge/-easy-brightgreen"> Given two binary trees, 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. <ins>**Example 1:**</ins> ``` Input: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3] Output: true ``` <ins>**Example 2:**</ins> ``` Input: 1 1 / \ 2 2 [1,2], [1,null,2] Output: false ``` <ins>**Example 3:**</ins> ``` Input: 1 1 / \ / \ 2 1 1 2 [1,2,1], [1,1,2] Output: false ``` ## Solution ```python= # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: if p is None and q is None: return True elif p is None or q is None: return False else: return (p.val == q.val) and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) ```