How to implement a binary search tree in Python?

Here is a quick example of a binary insert: class Node: def __init__(self, val): self.l_child = None self.r_child = None self.data = val def binary_insert(root, node): if root is None: root = node else: if root.data > node.data: if root.l_child is None: root.l_child = node else: binary_insert(root.l_child, node) else: if root.r_child is None: root.r_child = … Read more

How do you validate a binary search tree?

Actually that is the mistake everybody does in an interview. Leftchild must be checked against (minLimitof node,node.value) Rightchild must be checked against (node.value,MaxLimit of node) IsValidBST(root,-infinity,infinity); bool IsValidBST(BinaryNode node, int MIN, int MAX) { if(node == null) return true; if(node.element > MIN && node.element < MAX && IsValidBST(node.left,MIN,node.element) && IsValidBST(node.right,node.element,MAX)) return true; else return false; … Read more