LeetCode 筆記 - 100. Same Tree

題目在此 100. Same Tree

給兩個 Binary Tree,請判斷是不是同一棵樹

解題思維

同學,這題這麼簡單自己做 (X

沒有啦,就用一樣的方式走訪兩棵樹,遇到不一樣的地方就回傳 False

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:

if p is None and q is None:
return True
if p is None or q is None:
return False

if p.val != q.val:
return False

if not self.isSameTree(p.left, q.left):
return False
if not self.isSameTree(p.right, q.right):
return False

return True

也許你也會想看看