Validate Binary Search Tree — LeetCode 98 Python Solution
- Problem
- #98
- Pattern
- Tree Traversal
- Reading time
- 4 min
- Source
- leetcode.com
The 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.
Example
- Input
- root = [2,1,3]
- Output
- true
Python solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
def dfs(root: Optional[TreeNode]) -> bool:
if root is None:
return True
if not dfs(root.left):
return False
nonlocal prev
if prev >= root.val:
return False
prev = root.val
return dfs(root.right)
prev = -inf
return dfs(root)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 98. Validate Binary Search Tree is filed here because LeetCode tags it Tree, Binary Tree and Binary Search Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
On study lists
This problem is on Blind 75, NeetCode 150, Grind 75 and Top Interview 150.
Frequently asked questions
- How hard is LeetCode 98. Validate Binary Search Tree?
- LeetCode 98. Validate Binary Search Tree is rated Medium on LeetCode.
- What is the time complexity of LeetCode 98. Validate Binary Search Tree?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 98. Validate Binary Search Tree?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 98. Validate Binary Search Tree cover?
- LeetCode 98. Validate Binary Search Tree is tagged Tree, Depth-First Search, Binary Search Tree and Binary Tree on LeetCode.