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
lowandhigh. That's why it starts at the root with the range-inftoinf. "Internally valid" means that the left subtree's values must all be smaller than the root, and the right subtree's values must all be larger. You pass the range down as you go into deeper subtrees to make sure that you're satisfying the bounds required by the various parent nodes.nvariable got theval,right,leftattributes, so it's aNode(object)or it's really refering to thenodevariable?nis aNodeobject. This code would be easier to understand if it had type annotations in addition to better function/variable names! :)if not n: return Trueline just applies when there's no nodes, while in reality that line also "escapes" the iterations when a node doesn't have right nor left children , returning the value True. Just as a reference, this code was written by a guy that goes for the name "Techlead" on YT, but the Binary search tree one isn't on YT, it's on a site called "CoderPro",featured as the free sample of a series of training videos, if anybody else is interested in looking the source material and the coder explanation of this code. Thanks for your help