class BSTUtils: minval = float('inf') prevval = float('-inf') def minDistanceBST(self, root): if root == None: return None self.minDistanceBST(root.left) self.minval = min(self.minval, abs(root.data - self.prevval)) self.prevval = root.data self.minDistanceBST(root.right) return self.minval tree = BinaryTreeNode(17) tree.left = BinaryTreeNode(10) tree.right = BinaryTreeNode(25) tree.left.left = BinaryTreeNode(7) tree.left.right = BinaryTreeNode(12) tree.right.left = BinaryTreeNode(19) tree.right.right = BinaryTreeNode(32) # BinaryTreeUtils().inorder_traversal(tree) print(BSTUtils().minDistanceBST(tree))
if tree.left and tree.left.data > tree.data: return False if tree.right and tree.right.data <= tree.data: return False if not validateBST(tree.left) or not validateBST(tree.right): return False return True tree = BinaryTreeNode(1) tree.left = BinaryTreeNode(2) tree.right = BinaryTreeNode(3) tree.left.left = BinaryTreeNode(4) tree.left.right = BinaryTreeNode(5) tree.right.left = BinaryTreeNode(6) tree.right.right = BinaryTreeNode(7) print(validateBST(tree)) tree = BinaryTreeNode(4) tree.left = BinaryTreeNode(2) tree.right = BinaryTreeNode(6) tree.left.left = BinaryTreeNode(1) tree.left.right = BinaryTreeNode(3) tree.right.left = BinaryTreeNode(5) tree.right.right = BinaryTreeNode(7)