This is my code:
def check_bst_validity(root_node):
def is_bst(node, min_val=float(‘-inf’), max_val=float(‘inf’), ancestors=set()):
if not node:
return None
if not min_val < node.key < max_val:
return node
ancestors.add(node)
if node.left in ancestors:
return node
left_invalid = is_bst(node.left, min_val, node.key, ancestors)
if left_invalid:
return left_invalid
if node.right in ancestors:
return node
right_invalid = is_bst(node.right, node.key, max_val, ancestors)
if right_invalid:
return right_invalid
ancestors.remove(node)
return None
return is_bst(root_node)
It is only able to check the left side ancestor for BST Tree validity and output the node that is causing the invalid tree. It is unable to check the right side ancestor and output the node that is causing the BST Tree to be invalid. I have tried moving the node.right in ancestors statement around but it seems to stop somewhere and cause it to not search the right side ancestor. Any assistance would be greatly appreciated.
I am expecting it to output the right side ancestor node that is causing the BST Tree to be invalid. If the left side statement works, I am not sure why the right side statement would not be working the same. I have tried moving it before the left side check statement and it doesn’t seem to check the right side regardless.
user24995660 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.