Skip to content

Commit fd40d33

Browse files
committed
Adding Efficient Solution for Problem - 98 - Validate BST
1 parent 89cb8b3 commit fd40d33

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Validate_BST/EfficientSolution.py

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
##==================================
2+
## Leetcode
3+
## Student: Vandit Jyotindra Gajjar
4+
## Year: 2020
5+
## Problem: 98
6+
## Problem Name: Validate Binary Search Tree
7+
##===================================
8+
#
9+
#Given a binary tree, determine if it is a valid binary search tree (BST).
10+
#
11+
#Assume a BST is defined as follows:
12+
#
13+
#The left subtree of a node contains only nodes with keys less than the node's key.
14+
#The right subtree of a node contains only nodes with keys greater than the node's key.
15+
#Both the left and right subtrees must also be binary search trees.
16+
#
17+
#Example 1:
18+
#
19+
# 2
20+
# / \
21+
# 1 3
22+
#
23+
#Input: [2,1,3]
24+
#Output: true
25+
#Example 2:
26+
#
27+
# 5
28+
# / \
29+
# 1 4
30+
# / \
31+
# 3 6
32+
#
33+
#Input: [5,1,4,null,null,3,6]
34+
#Output: false
35+
#Explanation: The root node's value is 5 but its right child's value is 4.
36+
class Solution:
37+
def isValid(self, root):
38+
return self.BST(root, float("-inf"), float("inf")) #Return True or False based on Helper method BST
39+
def BST(self, root, minVal, maxVal): #Defining helper method BST
40+
if root is None: #Condition-check:If root is empty
41+
return True #We return True
42+
if root.val <= minVal or root.val >= maxVal: #Condition-check:If root's value is less than or equal to min value or greater than equal to max value
43+
return False #We return False
44+
validLeft = self.BST(root.left, minVal, root.val) #Initialize validLeft by using helper method
45+
validRight = self.BST(root.right, root.val, maxVal) #Initialize validRight by using helper method
46+
return validLeft and validRight #If niether of is False, we return False or True for both True values

0 commit comments

Comments
 (0)