简繁EN

LeetCodeNo. 014

[LeetCode with Python] 100. Same Tree

Contents

Problem

Problem page: https://leetcode.com/problems/same-tree/
Topics: Tree, Depth-first Search
Difficulty: Easy

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.


Analysis

Check whether two binary trees are equal. Recursive backtracking is a common approach here.


Code

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:

# @param p, a tree node
# @param q, a tree node
# @return a boolean
def isSameTree(self, p, q):
if None == p and None == q:
return True
elif (None == p and None != q) or (None != p and None == q):
return False
else:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

Article link: https://xnerv.wang/en/leetcode-same-tree/