Python implementation example. This example uses type annotations. However, since the Node class uses itself, we need to include as the first line of the module:
from __future__ import annotations
Otherwise, you will get the name 'Node' is not defined error. This example also uses the data class as an example. To check if this is a BST, it uses recursion to check the values of the left and right nodes.
"""Checks if Binary Search Tree (BST) is balanced""" from __future__ import annotations import sys from dataclasses import dataclass MAX_KEY = sys.maxsize MIN_KEY = -sys.maxsize - 1 @dataclass class Node: value: int left: Node right: Node @property def is_leaf(self) -> bool: """Check if node is a leaf""" return not self.left and not self.right def is_bst(node: Node, min_value: int, max_value: int) -> bool: if node.value < min_value or max_value < node.value: return False elif node.is_leaf: return True return is_bst(node.left, min_value, node.value) and is_bst( node.right, node.value, max_value ) if __name__ == "__main__": node5 = Node(5, None, None) node25 = Node(25, None, None) node40 = Node(40, None, None) node10 = Node(10, None, None)
Vlad Bezden Jan 16 '19 at 0:10 2019-01-16 00:10
source share