简繁EN

LeetCodeNo. 014

【LeetCode with Python】 100. Same Tree

目录

题目

原题页面:https://leetcode.com/problems/same-tree/
题目类型:Tree, Depth-first Search
难度评价: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.


分析

判断两个二叉树是否相等。常见的二叉树递归回溯算法。


代码

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)

本文地址:https://xnerv.wang/leetcode-same-tree/