150強訪談中等

相同的二元樹

「相同二元樹」問題的詳細指南和 Python 實作。

問題陳述

中等

給定兩個二元樹 p 和 q 的根,寫一個函數來檢查它們是否相同。

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

這些樹被表示為級別順序列表。實作函數 isSameTree(p: list, q: list) -> bool

約束條件
  • The number of nodes in both trees is in the range [0, 100]
  • -10000 <= Node.val <= 10000

範例

Example 1
Input
[1,2,3], [1,2,3]
Output
True
Explanation

Both trees have the same structure and values.

Example 2
Input
[1,2], [1,None,2]
Output
False
Explanation

In the first tree, 2 is the left child. In the second tree, 2 is the right child. Different structures.

Example 3
Input
[1,2,1], [1,1,2]
Output
False
Explanation

Same structure but different values at the children.

Need a Hint?
考慮使用樹特定的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。