Same Tree 解題教學:3 種解法完整比較|LeetCode 100 Best Practice

Same Tree 解題教學示意圖|LeetCode 100

本文完整拆解 LeetCode 100 Same Tree 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Same Tree 一次弄懂。

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link


Given the roots of two binary trees p and q, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

 

Example 1:

Input: p = [1,2,3], q = [1,2,3]
Output: true

Example 2:

Input: p = [1,2], q = [1,null,2]
Output: false

Example 3:

Input: p = [1,2,1], q = [1,1,2]
Output: false

 

Constraints:

  • The number of nodes in both trees is in the range [0, 100].
  • -104 <= Node.val <= 104

Python

				
					# time complexity: O(n)
# space complexity: O(n)
from typing import Optional


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 == None and q == None:
            return True
        if p == None or q == None:
            return False
        if p.val != q.val:
            return False
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)


p = TreeNode(1)
p.left = TreeNode(2)
p.right = TreeNode(2)

q = TreeNode(1)
q.left = TreeNode(2)
q.right = TreeNode(2)

print(Solution().isSameTree(p, q))
				
			

Same Tree 解題思路

判斷兩棵樹是否完全相同,是最純粹的結構遞迴:同時走訪兩棵樹,在每個位置比較三件事——兩邊是否都為空、值是否相同、左右子樹是否也相同。只要把終止條件寫清楚,主體就只有一行。

Same Tree 演算法步驟

  1. 若 p 與 q 都是 null,回傳 true。
  2. 若其中一個是 null(另一個不是),回傳 false。
  3. 若 p.val 不等於 q.val,回傳 false。
  4. 回傳 isSameTree(p.left, q.left) 與 isSameTree(p.right, q.right) 的邏輯且。

Same Tree 複雜度分析

項目複雜度
時間複雜度O(n)
空間複雜度O(h)

最多走訪兩棵樹的所有節點各一次,時間為 O(n),n 是較小那棵樹的節點數(因為不同就提早返回)。空間是遞迴深度 O(h),最壞為 O(n)。

Same Tree 的邊界情況與常見錯誤

  • 兩棵都是空樹時必須回傳 true。
  • 結構相同但值不同、值相同但結構不同,都要能正確判為 false。
  • 提早返回能大幅減少實際走訪量。
  • 改用迭代時要同時推入兩棵樹的節點配對,不能分開走訪。

Same Tree 其他解法比較

解法時間空間說明
各自序列化後比較字串O(n)O(n)可行但要處理 null 標記避免歧義
BFS 逐層比較O(n)O(n)需要佇列,空間較大
同步遞迴比較O(n)O(h)本文採用