Leetcode 100:相同的樹(最詳細的解法!!!)
阿新 • • 發佈:2019-01-03
給定兩個二叉樹,編寫一個函式來檢驗它們是否相同。
如果兩個樹在結構上相同,並且節點具有相同的值,則認為它們是相同的。
示例 1:
輸入: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
輸出: true
示例 2:
輸入: 1 1
/ \
2 2
[1,2], [1,null,2]
輸出: false
示例 3:
輸入: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
輸出: false
解題思路
這個問題同樣使用遞迴很輕鬆就可以解決,關鍵就是要理清楚遞迴函式的意義。我們判斷p
和q
的root、left、right
的值是不是相同即可。這裡我們要考慮好終止條件(p、q
是不是空)
class Solution:
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if p and q:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
if p == None and q == None:
return True
else:
return False
同樣的,對於可以用遞迴解決的問題,我們都應該思考一下怎麼可以通過迭代去解決。那這個問題怎麼通過迭代解決呢?那麼我們就會用到stack
,通過stack
class Solution:
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
q = [(p, q)]
while q:
node1, node2 = q.pop(0)
if node1 and node2 and node1.val == node2.val:
q.append((node1.left, node2.left))
q.append((node1.right, node2.right))
else:
if node1 != node2: # node1 == None and node2 != None node1 != None and node2 == None
return False
return True
如有問題,希望大家指出!!!