0

So this is my code below, my thought process is that if the smallest value in the tree is less than the root and the largest value in the tree is greater than the root it should check if the BST is valid

    def min(self):
       while self.left:
           self.root = self.left
    return self.root

    def max(self):
        while self.right:
            self.root = self.right
    return self.value

    def valid(self):
        min = min(self.left)
        max = max(self.right)

        if self.root > min and self.root < max:
            return True
1
  • What makes you think it would not work? Commented Aug 1, 2018 at 0:31

1 Answer 1

1

Don't reuse the names min and max. They already refer to built-in functions.

Your min and max functions change the tree, by changing self.root.

You should be validating that the values of the left and right child nodes are correct relative to the parent node, then validating that each of the BSTs rooted at those child nodes is itself valid.

class Node:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right
    def valid(self):
        if self.left and self.left.value > self.value:
            return False
        if self.right and self.right.value < self.value:
            return False
        return all(node.valid() for node in (self.left, self.right) if node)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.