Skip to main content

Validate Binary Search Tree

Question

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

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

Solution

all//Validate Binary Search Tree.py


# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None

class Solution:
def isValidBST(self, root):
return self.helper(root, float('-inf'), float('inf'))

def helper(self, node, lower, upper):
if not node:
return True
if node.val <= lower or node.val >= upper:
return False
return self.helper(node.right, node.val, upper) and self.helper(node.left, lower, node.val)