150強訪談中等

計算二元樹中的好節點數

“計算二元樹中的好節點”問題的詳細指南和 Python 實作。

問題陳述

中等

給定一個二元樹根,如果從根到 X 的路徑中不存在值大於 X 的節點,則樹中的節點 X 被命名為良好。

傳回二元樹中好節點的數量。

該樹被表示為一個級別順序列表。實作函數 goodNodes(root: list) -> int

約束條件
  • The number of nodes in the binary tree is in the range [1, 100000]
  • -10000 <= Node.val <= 10000

範例

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

Root 3 is always good. Node 4 (3<=4, good). Node 3 under node 1 (3<=3, good). Node 5 (3<=4<=5, good). Node 1 is not good (3>1). Node 1 under 4 is not good (4>1). Total: 4 good nodes.

Example 2
Input
[3,3,None,4,2]
Output
3
Explanation

Root 3 is good. Node 3 (left child, 3<=3, good). Node 4 (3<=3<=4, good). Node 2 is not good (3>2). Total: 3.

Example 3
Input
[1]
Output
1
Explanation

The root is always a good node.

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

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