
Code
The Sorting Tree
A binary search tree (BST) keeps one rule at every node:
- everything in the left subtree is smaller, and
- everything in the right subtree is bigger.
That rule means you can find a value with one decision per level. It's like binary search, but in a structure you can keep adding to.
def contains(node, value):
if node is None:
return False
if value == node.value:
return True
if value < node.value:
return contains(node.left, value)
return contains(node.right, value)
Insert follows the same path down and attaches a new node at the empty spot it reaches. A neat bonus: an inorder walk of a BST visits the values in sorted order!
Speed
In a balanced tree each step halves the work: O(log n). But insert already-sorted values and every node goes right, the "tree" becomes a linked list and searches take O(n). Production code uses self-balancing trees (red-black, AVL) to avoid this.
Assignment
insert(node, value)returns the root of the tree withvalueadded. IfnodeisNone, return a newBSTNode(value). Smaller values go left, bigger go right, duplicates are ignored.contains(node, value)returnsTrueorFalse.
insert(node, value)returns the root of the tree withvalueadded. IfnodeisNone, return a newBSTNode(value). Smaller values go left, bigger go right, duplicates are ignored.contains(node, value)returnsTrueorFalse.
main.py Python sleeping
Press Run to try your code, then Check to test it.