150強訪談簡單

驗證二元搜尋樹

“驗證 BST”問題的詳細指南和 Python 實作。

問題陳述

簡單

給定二元樹的根,確定它是否是有效的二元搜尋樹(BST)。

有效的 BST 定義如下:

- 節點的左子樹僅包含鍵嚴格小於該節點鍵的節點。

- 節點的右子樹僅包含鍵嚴格大於該節點鍵的節點。

- 左右子樹也必須是二元搜尋樹。

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

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

範例

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

The left child 1 < root 2, and right child 3 > root 2. Valid BST.

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

The right child of root is 4, which is less than 5. Also, node 3 is in the right subtree of 5 but is less than 5. Not a valid BST.

Example 3
Input
[5,4,6,None,None,3,7]
Output
False
Explanation

Node 3 is in the right subtree of 5 but has value 3 < 5. Not valid.

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

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