ntree.ai
ntree.aiValidate Binary Search Tree

Validate Binary Search Tree

mediumsolvedattempted

Given the root of a binary tree, return true if it is a valid binary search tree.

A binary tree is a valid binary search tree if for every node:

  • every value in its left subtree is less than the node value
  • every value in its right subtree is greater than the node value

Example 1:

5
3
2
4
8
Input:  root = [5, 3, 8, 2, 4]
Output: true

Example 2:

5
4
6
3
7
Input:  root = [5, 4, 6, null, null, 3, 7]
Output: false
Explanation: 3 is in the right subtree of 5, so it has to be greater than 5.

Constraints:

  • 1 <= the number of nodes in the tree <= 10^4
  • -2^31 <= Node.val <= 2^31 - 1
# Definitions:
# class TreeNode:
# def __init__(self, val=0, left=None, right=None, parent=None):
# self.val = val
# self.left = left
# self.right = right
# self.parent = parent
 
def isValidBST(root: TreeNode) -> bool:
pass
 

Press Visualise to step through your code.