So I was looking into an "Easy Python code example" that checks if a set of nodes form a Binomial tree or not, it should evaluate and return either True or False, the full code is the following:
class Node(object):
def __init__(self, val, left = None, right = None):
self.val = val
self.right = right
self.left = left
class Solution(object):
def _isValidBSTHelper(self, n , low, high):
if not n:
return True
val = n.val
if ((val > low and val < high) and
self._isValidBSTHelper(n.left, low ,n.val) and
self._isValidBSTHelper(n.right, n.val, high)):
return True
return False
def isValidBST(self, n):
return self._isValidBSTHelper(n, float('-inf'), float('inf'))
## (_5_)
# / \
# (_4_) (_7_)
# / \ / \
#(_3_) (empty)(_6_) (_8_)
node = Node(5)
node.right = Node(7)
node.right.right = Node(8)
node.left = Node(4)
node.left.left = Node(3)
node.right.left = Node(6)
print(Solution().isValidBST(node))
The comments are supposed to be just a visual representation of the nodes that were expressed below.
I'm having a hard time understanding why is float('-inf'), float('inf') needed in
def isValidBST(self, n):
return self._isValidBSTHelper(n, float('-inf'), float('inf'))
and how low, high, and n.val values function in
class Solution(object):
def _isValidBSTHelper(self, n , low, high):
if not n:
return True
val = n.val
Any help would be appreciated in understanding how does this code works, thanks