Top 150-InterviewEinfach

BST validieren

Detaillierte Anleitung und Python-Implementierung für das Problem „Validate BST“.

Problemstellung

Einfach

Bestimmen Sie anhand der Wurzel eines Binärbaums, ob es sich um einen gültigen binären Suchbaum (BST) handelt.

Ein gültiger BST ist wie folgt definiert:

- Der linke Teilbaum eines Knotens enthält nur Knoten mit Schlüsseln, die strikt kleiner als der Schlüssel des Knotens sind.

- Der rechte Teilbaum eines Knotens enthält nur Knoten mit Schlüsseln, die unbedingt größer als der Schlüssel des Knotens sind.

- Sowohl der linke als auch der rechte Teilbaum müssen ebenfalls binäre Suchbäume sein.

Der Baum wird als Liste mit Ebenenreihenfolge dargestellt. Implementieren Sie eine Funktion isValidBST(root: list) -> bool.

Einschränkungen
  • The number of nodes in the tree is in the range [1, 10000]
  • -2^31 <= Node.val <= 2^31 - 1

Beispiele

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?
Erwägen Sie die Verwendung von Trees-spezifischen Datenstrukturen wie Sets oder Heaps.
Edge Cases to Watch
  • Leere Eingabestrukturen
  • Einzelelementeingaben
  • Große numerische Grenzen

Bereit zur Lösung?

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

Im Editor öffnen
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

Empfohlene Python-Ressourcen

Erweitern Sie Ihr Wissen mit zugehörigen interaktiven Tutorials, Spickzetteln und Codevergleichen.