BST Insert And Delete With Successor (Python)

Implement a binary search tree supporting insert and delete using in-order successor for two-child nodes.

PythonData Integrity

Code

pythonsnippet
27 lines
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None


class BST:
    def __init__(self):
        self.root = None

    def insert(self, val):
        if not self.root:
            self.root = TreeNode(val)
            return
        cur = self.root
        while True:
            if val < cur.val:
                if not cur.left:
                    cur.left = TreeNode(val)
                    return
                cur = cur.left
            else:
                if not cur.right:
                    cur.right = TreeNode(val)
                    return
                cur = cur.right

How it works

BST Insert And Delete With Successor (Python) comes down to the classes TreeNode and BST and the functions __init__ and insert.

Repetition is confined to while True — the rest of the file is straight-line.

Applying it

The primary signature is def insert(self, val)

insert is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

def __init__(self, val):
    self.val = val
    self.left = None
    self.right = None
def insert(self, val):
    if not self.root:
        self.root = TreeNode(val)
        return
    cur = self.root
    while True:
        if val < cur.val:
            if not cur.left:
                cur.left = TreeNode(val)
                return
            cur = cur.left
        else:
def __init__(self):
    self.root = None

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. The file defines `__init__`, `insert` at load time.