Skip to content

Commit

Permalink
added the new question for validating binary search tree
Browse files Browse the repository at this point in the history
  • Loading branch information
b-izad committed Jul 7, 2023
1 parent 425f24a commit 198de82
Showing 1 changed file with 50 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
'''98. Validate Binary Search Tree
Medium
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 less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
Input: root = [2,1,3]
Output: true
Example 2:
Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.'''

# 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):
def helper(node, lower=float('-inf'), upper=float('inf')):
if not node:
return True

val = node.val
if val <= lower or val >= upper:
return False

if not helper(node.right, val, upper):
return False
if not helper(node.left, lower, val):
return False
return True

return helper(root)

0 comments on commit 198de82

Please sign in to comment.