# Definition for a binary tree node.# 用遞歸的思想來做題。# 首先比較自身節點是否相同,然後比較節點左兒子,最後比較右兒子class TreeNode: def __init__(self, x): self.val = x self.left = None s ...
# 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:
# 當兩個節點都為None意味著情況相同, 返回真
if p == None and q == None:return True
# 兩個節點有一個為None返回False
if p == None and q!= None:return False
if p != None and q == None:return False
# 若值不同同樣返回FALSE
if q.val != p.val : return False
# 最後自身遞歸調用,分別比較左兒子和右兒子。
return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)