简繁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/zh-tw/leetcode-same-tree/