0%
Loading ...

【Leetcode 筆記】100. Same Tree

image 1723788312694

題目解釋

給定兩個 binary tree pqroot
寫一個函數來檢查它們是否相同。

如果兩個二元樹 結構相同節點具有相同的值 ,則認為它們是相同的。

範例

file

  • 輸入: p = [1, 2, 3], q = [1, 2, 3]
  • 輸出: True

pq 的結構與 node 的值皆相同。

最佳解法

如果 pq 同時 都沒有了,代表我們應該 return True 回去。

但是如果 p 先沒了或是 q 先沒了,
就代表他們不是同棵樹,所以要 return False。

當然,p 的值跟 q 的值不一樣的話也是不行的❗

程式碼

class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if (not p) and (not q):
            return True

        if (p and not q) or (not p and q) or (p.val != q.val):
            return False
        else:
            return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

時間複雜度

O(n),n 是 binary tree 的 node 個數。

空間複雜度

O(h),h 是 binary tree 的高度,長的平均的話最好情況是 O(log n)

結語

善用 return 的值。

數據女巫 𝔻.𝕡𝕪𝕤 🔮

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.