LeetCode:判斷相同的二叉樹
給定兩個二叉樹,編寫一個函數來檢驗它們是否相同。 如果兩個樹在結構上相同,並且節點具有相同的值,則認爲它們是相同的。 示例 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
思路:同時遍歷2棵二叉樹,發現不同便終止,否則繼續
定義二叉樹:
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
遞歸實現:
# 遞歸
def isSameTree2(self, p: TreeNode, q: TreeNode) -> bool:
if not p and not q: return True
if p and q and p.val==q.val:
return self.isSameTree(p.left,q.left) and self.isSameTree(p.rihgt,q.right)
迭代實現:
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
stack=[(p,q)]
while stack:
a,b = stack.pop()
if not a and not b:
continue
if a and b and a.val==b.val:
stack.append((a.right,b.right))
stack.append((a.left,b.left))
else:
return False
return True