150強訪談中等

另一棵樹的子樹

「另一棵樹的子樹」問題的詳細指南和 Python 實作。

問題陳述

中等

給定兩個二元樹 root 和 subRoot 的根,如果 root 的子樹具有相同的結構和 subRoot 的節點值,則傳回 true,否則傳回 false。

二元樹的子樹是由樹中的一個節點和該節點的所有後代組成的樹。樹也可以被視為其自身的子樹。

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

約束條件
  • The number of nodes in the root tree is in the range [1, 2000]
  • The number of nodes in the subRoot tree is in the range [1, 1000]
  • -10000 <= root.val <= 10000
  • -10000 <= subRoot.val <= 10000

範例

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

The subtree rooted at node 4 in the main tree matches subRoot exactly.

Example 2
Input
[3,4,5,1,2,None,None,None,None,0], [4,1,2]
Output
False
Explanation

The subtree rooted at 4 in the main tree has an extra node 0 under 2, so it doesn't match subRoot.

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 資源

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