BST Insert And Delete With Successor (Python)
Implement a binary search tree supporting insert and delete using in-order successor for two-child nodes.
Code
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.rightHow 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
Markdown Heading OutlineExtract ATX headings from Markdown into an indented outline with line numbers and per-level counts, ignoring code fences.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. The file defines `__init__`, `insert` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.