Top 150 InterviewЛегко

Validate BST

Detailed guide and Python implementation for the 'Validate BST' problem.

Постановка задачи

Легко

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

A valid BST is defined as follows:

- The left subtree of a node contains only nodes with keys strictly less than the node's key.

- The right subtree of a node contains only nodes with keys strictly greater than the node's key.

- Both the left and right subtrees must also be binary search trees.

The tree is represented as a level-order list. Implement a function 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?
Consider using Trees-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Готовы решить?

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

Расширьте свои знания с помощью соответствующих интерактивных руководств, шпаргалок и сравнений кода.

Учебник по Python

Циклы Python

Узнайте, как использовать циклы Python для перебора данных. Освойте циклы for, while, прерывание, продолжение и лучшие практики работы с циклами с помощью интерактивных примеров.

Посмотреть ресурс
Практическое руководство

Как отсортировать список в Python

Узнайте, как сортировать список в Python с помощью метода sort() и функции sorted(). Ознакомьтесь с примерами пользовательской сортировки ключей и обратного порядка.

Посмотреть ресурс
Шпаргалка

Шпаргалка по строковым методам Python

Полное справочное руководство по манипулированию строками в Python. Мастер форматирования, поиска, разделения, замены и проверки свойств строк.

Посмотреть ресурс
Сравнение языков

Python против JavaScript: какой язык программирования лучше?

Всестороннее сравнение Python и JavaScript. Изучите синтаксические различия, производительность, варианты использования (серверная и клиентская части) и примеры кодирования.

Посмотреть ресурс