- Learn
- Computer Science & IT
- Programming
- Data Structures and Algorithms
- Binary Search Trees
Trees and Binary Search Trees
IntermediateLesson 6 of 10 in Data Structures and Algorithms Course
What you will learn
- Name the parts of a tree, measure depth and height, and store trees in Python so that recursive functions can work with them.
- Use tree vocabulary and measure depth and heightIdentify the root, parents, children, leaves and subtrees of a tree, measure depth and height, and recognize binary, full, complete and perfect trees.
- Store trees in Python and compute with them recursivelyRepresent general and binary trees with node objects and write recursive functions for size and height that handle the empty tree correctly.
- Use tree vocabulary and measure depth and height
- Visit every node of a tree in preorder, inorder, postorder and level order, with recursion, an explicit stack or a queue, and use these orders to solve problems.
- Visit nodes in preorder, inorder and postorderTrace the three depth-first orders on a binary tree, write them recursively and choose the order that fits a task.
- Traverse without recursion using an explicit stackReplace the call stack with your own stack to produce preorder, inorder and postorder, and trace the stack step by step.
- Traverse level by level with a queueVisit nodes in order of depth with a queue, group them into levels and compare the memory use of breadth-first and depth-first traversal.
- Solve problems with traversalsUse traversal orders to evaluate expression trees, save and rebuild trees, and compute properties from the bottom up.
- Visit nodes in preorder, inorder and postorder
- Apply the binary search tree ordering rule to find, add and remove keys, and predict how the order of insertions shapes the tree and its speed.
- Find keys using the binary search tree propertyState the ordering rule of a binary search tree, search for keys and the minimum and maximum, and check whether a tree really is a binary search tree.
- Insert keys and predict the shape of the treeAdd keys to a binary search tree, explain how insertion order determines the height, and estimate the cost of building a tree.
- Delete keys from a binary search treeRemove a key in each of the three cases (no child, one child, two children) while keeping the ordering rule, and avoid the usual linking errors.
- Find keys using the binary search tree property
- Explain why height decides the cost of search-tree operations and keep an AVL tree height-balanced by rotating nodes after insertions and deletions.
- Explain what AVL balance guaranteesCompute balance factors, decide whether a tree satisfies the AVL condition and explain why that condition keeps the height logarithmic.
- Perform single and double rotationsCarry out left and right rotations that preserve the key order, and pick the single or double rotation that fixes each of the four imbalance cases.
- Insert and delete keys in an AVL treeCombine BST insertion and deletion with height updates and rotations on the way back to the root, and trace complete sequences of operations.
- Explain what AVL balance guarantees
- Store key-value pairs in a balanced search tree, answer questions that depend on key order, and choose between a search tree, a hash table and a sorted array.
- Answer order queries with floor, ceiling, successor and rangesUse a search tree as a map that also finds the nearest keys below and above a value, the next and previous keys, and all keys in a range.
- Answer rank and select queries with subtree sizesStore subtree sizes in the nodes and use them to find the position of a key, the key at a given position, range counts and medians.
- Answer order queries with floor, ceiling, successor and ranges
Binary Search Trees study guide
1Tree structure and Python nodes
Trees describe data whose parts contain smaller parts: folders, expressions, and search indexes all have this shape. The vocabulary lets you name a position without drawing the whole structure. Depth and height then turn that picture into measurements you can use to analyze code. This chapter connects those measurements with Python node objects and shows how a short recursive function can combine answers from smaller subtrees.
1.1 Parts, distances, and binary tree shapes
A rooted tree joins nodes with edges. The root has no parent; every other node has exactly one. There is one path from the root to each node, with no cycles. For a nonempty tree with nodes, there are edges: each node except the root contributes its link to a parent.
Name a node's surroundings
A node's children are directly below it. Children of the same parent are siblings. Ancestors lie on the path toward the root; descendants lie below the node. A leaf has no children, while an internal node has at least one. A subtree contains its root and all that root's descendants.
Use this binary tree throughout the example:
A
/ \
B C
/ \ \
D E F
/
G
B's subtree contains B, D, E, and G. D, G, and F are leaves; A, B, C, and E are internal nodes. G's ancestors are E, B, and A. There are 7 nodes and 6 edges. If an item had two parents, there would be two routes from the root to it, so the structure would no longer be a tree.
Count edges for depth and height
Depth counts edges from the root to a node. Height counts the longest downward path from a node to a leaf. The root has depth 0, every leaf has height 0, and an empty tree has height −1. A level groups nodes of the same depth.
G has depth 3. E has height 1, B has height 2, and A has height 3. Level 2 contains D, E, and F. A leaf can occur above the deepest level: D has depth 2, while G has depth 3. Counting the nodes on a path would give an answer one larger. Some books use that convention, so compare definitions before comparing heights.
For any node, its depth plus its height is at most the tree height. It equals the tree height only when a longest root-to-leaf path passes through that node.
Distinguish common shapes
A binary tree gives each node at most two children, labeled left and right. A lone left child and a lone right child produce different shapes. With 3 nodes there are 5 binary tree shapes. Across a binary tree with nodes, the child-link slots contain edges and empty links.
| Shape | Required structure |
|---|---|
| Full | Every node has either 0 or 2 children. |
| Complete | All levels except possibly the last are filled; the last fills from the left. |
| Perfect | Every internal node has two children, and all leaves have the same depth. |
The pictured tree is none of these three special shapes. A perfect tree of height 3 has 15 nodes and 8 leaves. In general, level holds at most nodes, and a perfect tree of height has nodes.
A nonempty binary tree with nodes has height between and . With 10 nodes, the range is 3 through 9: a complete shape reaches 3, and a chain reaches 9. This difference controls the cost of algorithms that follow one downward path.
Key Takeaways
- A subtree includes its root and every descendant.
- Depth measures the path from the root; height measures the longest path down to a leaf.
- Here a leaf has height 0 and the empty tree has height −1.
- Full, complete, and perfect describe different structural rules.
- A binary tree has empty child links and height at most .
1.2 Node objects and recursive calculations
A tree algorithm starts with a reference to the root. Following a child link gives the same kind of structure on a smaller scale. Python node objects make this recursive structure explicit, including the empty subtrees where recursion stops.
Choose child links that fit the tree
A general tree allows any number of children. Give each object its own child list:
class TreeNode:
def __init__(self, value):
self.value = value
self.children = []
The list's order determines the order of the children. A folder can hold many files or folders, so this representation fits it directly. For a binary tree, preserve the two different positions:
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
None means an empty subtree. An optional parent link supports upward movement, but every insertion, deletion, or rotation must then maintain that link too. Creating a child and assigning root.left = child does not update child.parent by itself.
Let the empty case carry the boundary
A binary tree is either empty or a node with two binary subtrees. Size adds both answers and includes the current node. Height takes the larger answer and adds one edge:
def size(node):
if node is None:
return 0
return 1 + size(node.left) + size(node.right)
def height(node):
if node is None:
return -1
return 1 + max(height(node.left), height(node.right))
A leaf has two empty children, so its height is . Its size is . Returning height 0 for None would make a leaf's height 1 and switch to counting nodes.
In the tree A with children B and C, B with children D and E, E with left child G, and C with right child F, the leaf heights return first. E gets height 1 from G and its empty right link. B gets 2 from D and E; C gets 1 from its empty left link and F. Finally A gets 3. The size calls add to 7.
The base case must run before reading node.left. Otherwise the first empty link causes an AttributeError. Handling None in one place also keeps nodes with only one child from needing separate versions of the recursive step.
Separate total work from stack depth
Both functions visit all nodes, taking time. Only calls on the current downward path remain active, so the call stack takes space, commonly written for nontrivial trees. A balanced shape has a short stack; a chain can have one active call per node.
A chain of 10,000 nodes exceeds a recursion limit of 1,000. The current limit is available through sys.getrecursionlimit(); an explicit stack avoids depending on it for deep trees.
Other representations answer different needs. A parent array gives each numbered node its parent's number, with −1 for the root. A left-child, right-sibling representation gives a general-tree node a link to its first child and a link to its next sibling. In that form, a right link means a sibling, so ordinary binary-tree height code would measure the representation's links, not the original general tree's levels.
Key Takeaways
- Use a child list for a general tree and separate left/right links for a binary tree.
- Handle
Nonebefore reading any node attribute. - Recursive size adds both subtree sizes; recursive height adds one to the larger height.
- These calculations take time and stack space proportional to height.
2Traversal orders and their uses
A tree has no single natural next node. The next node depends on whether you need a parent first, children first, sorted keys, or the shallowest remaining item. You will trace each visit order and see how a stack or queue keeps the unfinished work. The same ideas lead to expression evaluation, saving and rebuilding tree shapes, and efficient bottom-up checks. Follow the changing state as well as the final output: it explains why each algorithm works.
2.1 Three ways to place the visit
A traversal visits every node once. In a depth-first traversal, you finish the work in one subtree before moving to the other. Preorder, inorder, and postorder change the moment when you process the current node; the left subtree still comes before the right.
Move one line to change the order
def preorder(node, out):
if node is None:
return
out.append(node.key)
preorder(node.left, out)
preorder(node.right, out)
Preorder visits the node, left, right. Move out.append(node.key) between the two calls for inorder: left, node, right. Move it below both calls for postorder: left, right, node. Each recursive call completes its entire subtree before returning to the next line.
The word "visit" means the task performed at that position: appending a key, printing a label, or combining results. Merely entering a recursive call is not the visit in an inorder or postorder traversal.
Expand subtrees in place
Take root A, with left child B and right child C. B has children D and E; E has left child G. C has right child F.
For preorder, write A first. Expand B's whole subtree as B D E G, then expand C's as C F. The result is A B D E G C F. Do not return to C just because it appears beside B in the drawing: that would start a level-order traversal.
For inorder, place A between its subtree results. B's subtree gives D B G E, while C's gives C F. Together they give D B G E A C F. G precedes E because G is E's left child; C precedes F because F is C's right child. A node with one child still has a specific left or right position.
For postorder, finish both children before the parent. D gives D, E's subtree gives G E, and then B is visited: D G E B. C's subtree gives F C. A comes last, yielding D G E B F C A.
Three quick checks help when tracing: the root is first in preorder, last in postorder, and between the complete left and right subtree outputs in inorder. These checks locate the root; you must apply the same rule recursively inside each subtree to verify the whole sequence.
Let dependencies choose the traversal
A folder listing that prints a folder before its contents suits preorder. Copying or saving a tree also naturally starts with the parent. A folder's total storage depends on its children, so postorder supplies their totals before computing the parent's total. Expression evaluation, subtree sizes, and heights use the same children-first dependency.
Inorder lists a BST's keys in sorted order because every left key is smaller than the node and every right key is larger. Inorder on an arbitrary binary tree follows positions; its keys need not be sorted.
Preorder and postorder also work for a general tree by processing each child in list order. Inorder has no single standard position among an arbitrary number of children.
Account for the output separately
With constant work per visit, every depth-first order takes time. Recursion keeps pending calls for a nontrivial tree. If out stores every visited key, that output list uses another space. A visitor that processes each key immediately avoids keeping that list; it does not change the visit order.
Key Takeaways
- Preorder handles the node before its subtrees; postorder handles it after both.
- Inorder places the node between the entire left and right subtree outputs.
- A single child's left/right position still matters in inorder.
- Use postorder when a parent needs results from its children.
- Inorder is sorted only when the tree satisfies the BST ordering rule.
- Separate traversal stack space from space used to store the output.
2.2 Keep pending work on an explicit stack
Recursion stores unfinished work in call frames. An explicit stack stores it in a Python list, using append to push and pop to remove the most recent entry. This gives you control over a deep traversal and lets an iterator pause after producing one key.
Preorder: push in reverse visit order
def preorder_iter(root):
if root is None:
return
stack = [root]
while stack:
node = stack.pop()
yield node.key
if node.right is not None:
stack.append(node.right)
if node.left is not None:
stack.append(node.left)
The right child goes on first so the left child comes off first. With root A, children B and C, B's children D and E, E's left child G, and C's right child F, start with [A]. After visiting A, the stack is [C, B], with the top on the right. Visiting B changes it to [C, E, D]; D leaves next. E then pushes G above C. The visits are A B D E G C F.
Pushing left before right produces A C F B E G D, a node-right-left traversal. A stack's last-in, first-out behavior reverses the order in which pending children are removed.
Inorder: remember the path back
def inorder_iter(root):
stack = []
current = root
while current is not None or stack:
while current is not None:
stack.append(current)
current = current.left
current = stack.pop()
yield current.key
current = current.right
The inner loop saves nodes whose left subtree is still being explored. When it reaches an empty link, the top node's left work is complete: pop it, visit it, then start its right subtree. The outer condition uses or because either a current subtree or a saved ancestor means work remains.
On the letter tree, the initial path pushes A, B, D. Visit D, then B. B's right subtree pushes E and G, producing G and then E. A follows, then C and F. The output is D B G E A C F. A one-child node needs no special rule; the same empty-link handling works.
On a BST, an iterator can stop at the third visit to return the third-smallest key. It need not build the full sorted list first. The stack remains available if iteration later resumes.
Postorder and its storage tradeoff
One simple iterative postorder method gathers node-right-left order and reverses the result. Reversing A C F B E G D gives D G E B F C A. This method stores all keys, so its extra result storage is even when the pending-node stack is small. A streaming single-stack version instead tracks whether a node's right subtree has already been visited before processing that node.
A full traversal still takes time. The depth-first pending stack has an bound, although its actual size depends on the shape and algorithm. Switching to level order requires a queue and left-first child insertion. Replacing the stack alone while keeping right-first insertion would list each level from right to left.
Key Takeaways
- An explicit stack replaces recursive pending work.
- Iterative preorder pushes the right child before the left.
- Iterative inorder saves the left path, visits a popped node, and then explores its right subtree.
- The inorder outer loop continues while either the stack or current node has work.
- Reversing node-right-left order gives postorder but stores the full result.
2.3 Use a queue to visit each level
Level order visits nodes by increasing depth, left to right within each level. It uses a first-in, first-out queue, so nodes discovered earlier leave before their children. This is useful when the shallowest answer matters or the output should be grouped by distance from the root.
Remove from the front and add at the back
from collections import deque
def level_order(root):
if root is None:
return
queue = deque([root])
while queue:
node = queue.popleft()
yield node.key
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
With root A, children B and C, B's children D and E, E's left child G, and C's right child F, the queue starts [A]. Visiting A leaves [B, C]. Visiting B leaves [C, D, E]; visiting C leaves [D, E, F]. D leaves before E adds G, so the final order is A B C D E F G.
Use deque.popleft() for a constant-time front removal. list.pop(0) shifts the remaining elements on every removal. In a wide tree, those repeated shifts can turn a linear traversal into work.
Freeze the current level's count
To build separate lists for levels, take the queue length before processing a level:
def levels(root):
if root is None:
return []
queue = deque([root])
result = []
while queue:
level = []
count = len(queue)
for _ in range(count):
node = queue.popleft()
level.append(node.key)
for child in (node.left, node.right):
if child is not None:
queue.append(child)
result.append(level)
return result
The letter tree gives [A], [B, C], [D, E, F], [G]. Reading a changing queue length as a stopping condition would mix newly added children into the current level. The fixed count marks exactly the nodes waiting at the round's start.
Stop at the shallowest leaf
The first leaf removed has minimum depth because no deeper node can leave before the shallower waiting nodes. Here D is the first leaf, at depth 2. A depth-first traversal can reach a deep leaf before finding a shallow leaf elsewhere, so its first leaf does not settle minimum depth.
For a general tree, append all of a node's children in their stored order. The same queue idea extends to graph search, where a visited record is also needed to avoid revisiting cycles or shared neighbors.
Measure the waiting frontier
Time is . Queue space is , where is maximum level width. It can hold the end of one level together with the start of the next. If A has children B and C and only B has children D and E, width is 2, yet after B leaves the queue is [C, D, E] of length 3. Thus width is an asymptotic bound, not an exact queue capacity.
A perfect 15-node tree has width 8, while a chain has width 1. Depth-first memory depends on height; breadth-first memory depends on width. Compare these shape measures before choosing a traversal for a large tree.
Key Takeaways
- A queue removes nodes in the order they were added.
- Add left children before right children for left-to-right levels.
- Capture the queue length once per level.
- The first leaf removed has minimum depth.
- Level order takes time and queue space; the queue can briefly exceed width.
2.4 Evaluate, serialize, and rebuild trees
Traversal order can do more than produce a list. It can place work before children, between them, or after their results are ready. The right choice preserves the information a task needs: operand grouping, missing child positions, or a result computed from smaller subtrees.
Evaluate an expression after its operands
For (3 + 4) * (5 - 2), an expression tree has * at the root. Its left child is + with leaves 3 and 4; its right child is - with leaves 5 and 2. Postorder computes and before combining them as .
Preorder prints the prefix form * + 3 4 - 5 2; postorder prints the postfix form 3 4 + 5 2 - *. With known binary operators, their operand counts fix the grouping. Plain inorder prints 3 + 4 * 5 - 2, which changes the expression's meaning. An inorder printer must include parentheses: ((3 + 4) * (5 - 2)).
A postfix evaluator pushes numbers. At an operator, it pops the right operand first, then the left, computes the result, and pushes it back. That order is essential for subtraction and division. For the example, the stack holds 7 after +, then 7 and 3 after -, then 21 after *.
Save the empty positions too
Preorder A B alone cannot tell whether B is A's left or right child. Serialization writes a marker for every empty link:
def serialize(node, out):
if node is None:
out.append("#")
return
out.append(str(node.key))
serialize(node.left, out)
serialize(node.right, out)
The letter tree A(B(D, E(G, empty)), C(empty, F)) becomes A B D # # E G # # # C # F # #. It contains 7 keys and 8 empty-link markers. Tokens must distinguish the marker from actual keys.
Rebuilding consumes tokens in the same recursive pattern: # returns None; otherwise create a node, rebuild its left subtree, and rebuild its right subtree. Writing and reading take time. Missing markers lose shape information, even when every key survives.
Combine two traversal views
With distinct keys, preorder plus inorder also determines a binary tree. The first preorder key is the root. Locate it in inorder; everything to its left belongs to the left subtree, and everything to its right belongs to the right subtree. Those counts split the remaining preorder sequence.
From preorder A B D E G C F and inorder D B G E A C F, A is root. The left part has 4 nodes, with preorder B D E G and inorder D B G E; the right part has preorder and inorder C F. Repeating the split places G to the left of E and F to the right of C. Postorder plus inorder works too, using the last postorder key as root. Preorder plus postorder does not distinguish a lone left child from a lone right child.
Combine several answers in one pass
A height-balance check can return (height, balanced) for each subtree. Combine the two heights and two verdicts at the parent, requiring their height difference to be at most 1. This visits every node once in time. Calling a fresh recursive height function at each node repeats subtree work and can take on a chain.
Key Takeaways
- Postorder supplies operand values before evaluating an operator.
- Plain inorder needs parentheses to preserve expression grouping.
- Preorder serialization needs empty-link markers to preserve shape.
- Distinct keys allow reconstruction from preorder plus inorder.
- Return height and balance together to avoid repeated subtree scans.
3Searching and changing binary search trees
A binary search tree adds an ordering rule to the links between nodes. That rule lets one comparison discard a whole subtree, but it does not promise a short search path. You will follow searches to the links where insertion happens, predict how arrival order changes the shape, and remove keys without breaking the order. Returning the updated subtree root is the central coding pattern: it handles ordinary child links and changes to the root in the same way.
3.1 Search with a rule for the whole subtree
A binary search tree stores comparable keys so that every key in a node's left subtree is smaller and every key in its right subtree is larger. This rule applies at every node and through every descendant. With distinct keys, it is equivalent to a strictly increasing inorder sequence.
Follow one search path
Insert the keys 50, 30, 70, 20, 40, 60, 80, 35, 45, 65 into an empty plain BST to obtain:
50
/ \
30 70
/ \ / \
20 40 60 80
/ \ \
35 45 65
Searching for 45 visits 50, 30, 40, and 45. At 50, discard the entire right subtree. At 30 and 40, discard their left subtrees. Searching for 62 visits 50, 70, 60, and 65, then reaches 65's empty left link. No remaining subtree can contain 62.
def find(node, key):
while node is not None:
if key == node.key:
return node
node = node.left if key < node.key else node.right
return None
A search inspects at most nodes. Its time is : logarithmic in a balanced shape and linear in a chain. The loop itself keeps only a node reference, using constant extra space.
Find the ends of the order
For the minimum, follow left links until the next one is empty. For the maximum, follow right links. The pictured tree gives 20 and 80. The minimum of the subtree rooted at 60 is 60, even though 60 has a right child. A minimum needs no left child; it need not be a leaf. These queries also cost .
Validate inherited limits
Checking only a node against its immediate children is too weak. Consider root 50, left child 30, right child 70, and 30's right child 60. Each immediate child is on the correct side of its parent, but 60 is inside 50's left subtree and violates the upper limit 50.
Pass an allowed interval down the recursion. Going left tightens the upper limit; going right tightens the lower limit. Use None for a missing bound so the check also works with nonnumeric comparable keys:
def valid(node, low=None, high=None):
if node is None:
return True
if low is not None and node.key <= low:
return False
if high is not None and node.key >= high:
return False
return (valid(node.left, low, node.key)
and valid(node.right, node.key, high))
This visits each node at most once, taking time. An inorder check that each key exceeds the previous key gives the same verdict.
Decide what equality means
In an ordered map, an existing key gets a new value; it does not create a second node. A multiset can store an occurrence count beside a key. An alternative puts equal keys consistently on one side and allows nondecreasing inorder output. If equality is allowed on both sides, ordinary search can still find one occurrence, but counting all occurrences may require exploring both sides. Keep the same duplicate rule in search, insertion, deletion, and validation.
Key Takeaways
- The BST rule constrains all descendants on each side, not just immediate children.
- Search follows one path, taking time.
- Minimum follows left links and need not be a leaf.
- Validate with inherited bounds or strictly increasing inorder output.
- Choose and maintain one rule for duplicate keys.
3.2 Insert keys and understand the resulting shape
Insertion follows the same comparisons as search. When a key is absent, the search ends at the exact empty link where the new leaf belongs. A plain BST keeps every existing node in place, so the arrival order determines the final shape.
Return the updated subtree root
def insert(node, key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
elif key > node.key:
node.right = insert(node.right, key)
return node
root = insert(root, 62)
This version stores distinct keys and leaves an existing key unchanged. A map would replace its value in the equality case. Each recursive caller reconnects the returned subtree to its child link. The final assignment also handles an empty whole tree: without it, the returned new node would never become root.
In the BST built from 50, 30, 70, 20, 40, 60, 80, 35, 45, 65, inserting 62 visits 50, 70, 60, and 65. It attaches 62 as 65's left child at depth 4. The tree height increases from 3 to 4; no other key moves.
Predict shape from arrival order
Inserting 10, 20, 30, 40, 50 builds a right chain of height 4. Inserting 30, 20, 40, 10, 50 gives height 2 with the same keys. A BST's ordering rule guarantees correct decisions, but it does not balance the paths.
For keys 1, 2, 3, the 6 insertion orders give 5 shapes. Orders 2, 1, 3 and 2, 3, 1 both give root 2 with children 1 and 3. The remaining 4 orders give chains. Different insertion orders can therefore produce the same shape, but the key set alone does not determine it.
When all distinct-key orders are equally likely, a search takes about comparisons on average. At one million keys this is about 28, compared with about 20 node visits in a perfectly balanced tree. Increasing timestamps or IDs arrive in sorted order, so random-order behavior is a poor guarantee for those workloads.
Add the work across a build
One insertion costs . For sorted keys, the successive comparison counts are 0, 1, 2, and so on:
For 1,000 keys, this is 499,500 comparisons. Repeated insertions take with short paths and in the chain case. A later inorder traversal is only ; it cannot undo expensive construction.
Build directly from sorted input
If the sorted keys are already available, choose a middle key as root and recursively build the two halves. Use index bounds to avoid copying slices:
def build(keys, lo, hi):
if lo >= hi:
return None
mid = (lo + hi) // 2
node = Node(keys[mid])
node.left = build(keys, lo, mid)
node.right = build(keys, mid + 1, hi)
return node
For 10, 20, 30, 40, 50, 60, 70, this gives root 40, children 20 and 60, and height 2. Each key creates one node, so construction is . Tree sort instead inserts input keys and reads inorder; balancing gives worst-case sorting, while a plain BST can take on sorted input.
Key Takeaways
- An absent key is inserted at the empty link where search ends.
- Assign each returned subtree root, including the whole tree root.
- Insertion order controls a plain BST shape and can produce a chain.
- Sorted insertion performs comparisons.
- Build a balanced tree from sorted keys in time using middle elements and index ranges.
- Tree sort combines tree construction with an inorder traversal.
3.3 Delete a key while keeping the order
Deletion must remove a key and leave every surviving subtree attached in a valid position. First search for the node. The repair depends on whether it has zero, one, or two children; the same rules apply when that node is the root.
Remove a leaf or promote one child
A leaf contributes no descendants, so replace its parent's link with None. In the running BST with root 50, left child 30 and right child 70, deleting leaf 20 leaves 30 with only its right child 40.
If the target has one child, return that child as the replacement subtree root. The child's entire subtree moves upward unchanged. In the running tree, 60 has right child 65; deleting 60 makes 65 the left child of 70. Nothing inside the promoted subtree needs to be reinserted.
Reduce two children to a simpler case
With two children, use the successor, the smallest key in the right subtree. Go right once, then follow left links. That node has no left child, so removing it is a leaf or one-child case. Copy its key and value into the target, then remove it from its old position. Using the predecessor, the maximum of the left subtree, also preserves the ordering.
To delete 30, its right subtree is rooted at 40 with children 35 and 45. The successor is 35. Replace 30's key by 35, then remove the old leaf 35. The new left subtree of 50 has root 35, children 20 and 40, and 40's right child 45.
Deleting the original root 50 instead uses successor 60. Because 60 has right child 65, the successor-removal step promotes 65 into 70's left link. The new root key is 60; its original left subtree remains intact. These are separate deletions starting from the original tree.
Code the replacement as a return value
For a key-only tree, the complete recursive pattern is:
def delete(node, key):
if node is None:
return None
if key < node.key:
node.left = delete(node.left, key)
elif key > node.key:
node.right = delete(node.right, key)
else:
if node.left is None:
return node.right
if node.right is None:
return node.left
successor = node.right
while successor.left is not None:
successor = successor.left
node.key = successor.key
node.right = delete(node.right, successor.key)
return node
Call it with root = delete(root, key). Returning the child handles deleting a one-child root; returning None handles deleting the last node. For a key-value map, copy the successor's value along with its key.
Track what was physically removed
Copying a successor key alone leaves two occurrences. The recursive removal in the right subtree is essential. Promoting the immediate right child while keeping all other links unchanged also fails in general: promoting 40 above 30 would need to preserve 20, 35, and 45, which do not fit as three direct children of 40.
Deletion follows the search path and possibly a path to a successor, so it costs . Successor deletion, also called Hibbard deletion, preserves key order but does not guarantee balance. Repeated mixed updates can worsen a plain tree's shape. A balanced tree also repairs heights along the path from the node actually removed.
Key Takeaways
- Delete a leaf by replacing its link with
None. - Replace a one-child node by its entire child subtree.
- For two children, copy the successor key/value and then remove the old successor.
- The successor has no left child but can have a right child.
- Return and reconnect the replacement subtree root.
- BST deletion preserves order but does not guarantee short paths.
4AVL balance and local rotations
A correct search tree can still be slow when its keys form a long chain. AVL trees prevent that shape by keeping the two child heights close at every node. You will calculate balance factors, relink small parts of a tree with rotations, and repair the path affected by an insertion or deletion. Stored heights make each local check cheap. The difference between insertion and deletion matters: deletion can shorten a repaired subtree and pass the problem upward.
4.1 Measure and maintain AVL balance
Search, insertion, and deletion follow paths whose cost depends on height. A plain BST with one million keys can have height anywhere from 19 to 999,999. A balanced search tree keeps height logarithmic after updates, so path-based queries and updates have a logarithmic worst-case bound.
Check every node's two heights
An AVL tree, named after Adelson-Velsky and Landis's 1962 method, is a BST in which each node's two child-subtree heights differ by at most 1. Here the balance factor is left height minus right height:
Every node must have balance factor −1, 0, or +1. Empty subtrees have height −1. Some texts reverse the subtraction; their signs reverse, while the permitted height difference stays the same.
In the running BST rooted at 50, both child subtrees have height 2, giving balance factor 0. Node 30 has child heights 0 and 1, giving −1. Node 70 has heights 1 and 0, giving +1. Node 60 has an empty left subtree and right leaf 65, giving −1. Node 40 and every leaf have factor 0. Thus the tree is AVL-balanced.
Checking the root alone misses internal problems. Root 4 with left chain 3, 2, 1 and right chain 5, 6, 7 has factor 0, but node 3 has +2 and node 5 has −2. The full tree fails the AVL rule.
Height balance is not equal size
AVL balance compares longest paths. It does not demand equal node counts, complete levels, or a perfect shape. A root with a perfect 7-node left subtree of height 2 and a 2-node right subtree of height 1 satisfies the rule when those subtrees are themselves AVL trees.
The fewest-node AVL shapes explain the height guarantee. Let be the minimum number of nodes for height . The two child heights must be at least and , giving:
The counts begin 1, 2, 4, 7, 12, 20, 33, 54. They equal for Fibonacci numbers with and . Exponential growth of these minimum counts makes height logarithmic, with leading bound about . One million nodes allow height at most 27, while the best binary shape has height 19.
Store heights so checks stay cheap
Each node stores its height. Read the two stored child heights and compute one plus their maximum in time. After changing a descendant, refresh the path back toward the root, children before parents. Calling a full recursive height calculation at every check would repeatedly scan subtrees and lose the update bound.
Red-black and 2-3 trees also guarantee logarithmic search and updates. A red-black tree's height is at most ; Java's TreeMap uses this family, as do typical C++ std::map implementations. Splay trees offer an amortized bound over a sequence, and treaps an expected bound over randomness; either can have a linear-time individual operation. AVL's stricter height rule favors short lookup paths and can require more deletion rotations.
Key Takeaways
- AVL balance requires child heights to differ by at most 1 at every node.
- Balance factors use left height minus right height here.
- Balanced heights do not require equal subtree sizes.
- The minimum-node recurrence gives logarithmic AVL height.
- Stored heights let each local check take constant time.
4.2 Rotate links without changing key order
A rotation moves a child above its parent while preserving inorder key order. It touches a constant number of links, so one rotation takes time. Its purpose in an AVL tree is to shorten the tall side without breaking the BST rule.
Preserve the middle subtree
For a right rotation, y has left child x. Before rotation, the order is . Afterward, x is the subtree root, y is x's right child, and the middle subtree T₂ becomes y's left child:
y x
/ \ / \
x T3 -> T1 y
/ \ / \
T1 T2 T2 T3
Every key of T₂ is greater than x and smaller than y, so its new position is valid. Losing T₂ during relinking drops keys; leaving it under x's right link conflicts with y's new position.
def rotate_right(y):
x = y.left
y.left = x.right
x.right = y
update(y)
update(x)
return x
def rotate_left(x):
y = x.right
x.right = y.left
y.left = x
update(x)
update(y)
return y
update refreshes stored height from the children. Update the node that moved down first, because the new top depends on its new height. The caller assigns the returned root to the parent's child link, or to the whole tree's root.
Use both balance factors
At an unbalanced node z, inspect the child on the taller side. With left-minus-right signs:
| Factor at z | Factor at taller child | Repair |
|---|---|---|
| +2 | 0 or +1 at left child | Right rotation at z |
| +2 | −1 at left child | Left at the child, then right at z |
| −2 | 0 or −1 at right child | Left rotation at z |
| −2 | +1 at right child | Right at the child, then left at z |
These are called left-left, left-right, right-right, and right-left cases. The child factor 0 matters after deletion. The sign at z alone identifies the tall side but cannot choose single versus double rotation.
Trace a straight path and a zig-zag
Insert 10, 20, 30. Node 10 has factor −2 and right child 20 has −1: a right-right case. Rotate left at 10, producing root 20 with children 10 and 30.
For a left-right case, start with root 20, left child 10, and right child 30 whose left child is 25. Insert 28 as 25's right child. Node 30 has factor +2, while child 25 has −1. First rotate left at 25, lifting 28 above 25. Then rotate right at 30, producing subtree root 28 with children 25 and 30. Reconnect it as 20's right child.
A single right rotation at 30 would lift 25, leaving 30 as its right child and 28 as 30's left child. That merely moves the imbalance to 25, now factor −2. The double rotation lifts the middle key 28 and distributes the smaller and larger keys to opposite sides.
After a rotation, verify three things: the inorder sequence is unchanged, every affected stored height reflects the new children, and the old parent points to the returned subtree root. When sizes are stored too, refresh them in the same lower-before-upper order.
Key Takeaways
- A rotation changes shape and preserves inorder order.
- The middle subtree moves across to the node that goes down.
- Choose the repair using both the node and its taller child's balance factors.
- A zig-zag needs a double rotation that lifts the middle key.
- Refresh the lower node before the new upper node.
- Reconnect the returned subtree root to its parent.
4.3 Repair the path after AVL updates
An AVL update starts with an ordinary BST insertion or deletion. The extra work occurs while returning toward the root: refresh the current node's height, inspect its balance factor, and rotate if needed. Only ancestors of the changed position can be affected.
Rebalance as recursion returns
Add self.height = 0 to the node initializer so each new leaf starts with a stored height. Use −1 for an empty child. This repair function uses the rotation functions from the preceding section:
def stored_height(node):
return -1 if node is None else node.height
def update(node):
node.height = 1 + max(stored_height(node.left),
stored_height(node.right))
def balance(node):
return (stored_height(node.left)
- stored_height(node.right))
def rebalance(node):
update(node)
if balance(node) > 1:
if balance(node.left) < 0:
node.left = rotate_left(node.left)
return rotate_right(node)
if balance(node) < -1:
if balance(node.right) > 0:
node.right = rotate_right(node.right)
return rotate_left(node)
return node
An AVL insert creates a leaf when it reaches None, reconnects the recursive result, and returns rebalance(node). A delete uses the same three BST cases, then returns rebalance(node) for every surviving nonempty node on its return path. Returning a child directly in the zero/one-child cases lets its caller continue the repair. Keep root = ... at the outer call too.
Insertion needs one repair site
Insert 10, 20, 30, 25, 28, 27. After 30, rotate left at 10 to get root 20 with children 10 and 30. Adding 25 needs no rotation. Adding 28 causes the left-right case at 30; the repaired right subtree has root 28 with children 25 and 30.
Adding 27 puts it to the right of 25. Now 20 has factor −2 and its right child 28 has +1. Rotate right at 28, then left at 20. The final root is 25, with left child 20 (left child 10) and right child 28 (children 27 and 30). Its height is 2. The same sequence in a plain BST has height 5.
At the lowest unbalanced ancestor after insertion, a single or double rotation restores that subtree's previous height. No higher ancestor needs another balance repair. One insertion therefore uses at most two primitive rotations at one site. Sorted keys 1 through 7 produce a perfect AVL tree of height 2; 1 through 15 produce height 3.
Deletion may pass the change upward
Start with root 20, left leaf 10, and right child 30 with right leaf 40. Delete 10. Node 20 has factor −2 and child 30 has −1; rotate left at 20 to get root 30 with children 20 and 40. The subtree height drops from 2 to 1. That drop can unbalance its parent, so deletion must continue checking ancestors.
In a separate tree, let 30 have both leaves 25 and 40. Deleting 10 again makes 20 factor −2, but 30 now has factor 0. A single left rotation gives root 30, left child 20 with right child 25, and right leaf 40. The height stays 2, so the height change stops there.
For a two-child deletion, begin upward repairs where the successor was physically removed, not merely where its key was copied. Recursion naturally includes this path. Deletion can need repairs at levels. Constant work at each level keeps both AVL insertion and deletion within worst-case time.
Key Takeaways
- Start with BST insertion or deletion, then refresh and repair affected ancestors.
- AVL insertion needs at most one single or double repair site.
- Deletion can lower a repaired subtree and require repairs higher up.
- A taller child with factor 0 uses a single rotation.
- Two-child deletion repairs the path from the successor removal.
5Ordered maps and position queries
Many programs need more than an exact key lookup. A schedule needs the next event, a log viewer needs a time interval, and a changing data set may need its middle key. A search tree can support all of these while keys are added and removed. This chapter follows the candidates kept during order queries and the subtree sizes used for position queries. It also compares these costs with a hash table and a sorted array so you can choose a structure for the work ahead.
5.1 Find nearby keys and report ranges
An ordered map stores distinct keys with values and supports queries about key order. A balanced BST provides put, get, and delete alongside minimum, maximum, neighbors, and ranges. put(k, v) replaces the value for an existing key; otherwise it inserts a node. A lookup get(k) returns the value or reports a missing key, for example with KeyError.
Keep the best candidate so far
The floor of k is the largest stored key at most k. The ceiling is the smallest stored key at least k. Both include equality. While finding a floor, a key smaller than k is a valid candidate, but a better one may be to its right:
def floor_key(node, key):
candidate = None
while node is not None:
if key == node.key:
return node.key
if key < node.key:
node = node.left
else:
candidate = node.key
node = node.right
return candidate
In the running tree rooted at 50, floor(62) visits 50, 70, 60, and 65. The candidate becomes 50, stays 50 at 70, becomes 60, and stays 60 at 65. The empty link ends the search with 60. Ceiling mirrors the comparisons and gives 65. Floor(40) is 40; floor(15) and ceiling(81) do not exist.
Distinguish equality from a strict neighbor
The successor is the next larger stored key; the predecessor is the next smaller. If a node has a right subtree, its successor is the minimum there. Otherwise, move toward the lowest ancestor whose left subtree contains the node. A search from the root can remember this ancestor without parent links.
For the running keys, successor(50) is 60, successor(45) is 50, and successor(80) is absent. Predecessor(60) is 50. A schedule asking for an event "at or after" a time uses ceiling. Asking for one "strictly after" uses the strict higher-key query. If an event exists at exactly that time, these answers differ.
Prune an inclusive range
To report keys from lo through hi in sorted order, modify inorder:
def keys_in_range(node, lo, hi, out):
if node is None:
return
if lo < node.key:
keys_in_range(node.left, lo, hi, out)
if lo <= node.key <= hi:
out.append(node.key)
if node.key < hi:
keys_in_range(node.right, lo, hi, out)
For 33 through 62, the output is 35, 40, 45, 50, 60. Skip a subtree only when the ordering rule rules it out. Reporting keys costs , or in a balanced tree. The output itself requires work proportional to its length. Full sorted iteration is .
Match the structure to the workload
A hash table gives average exact lookup and insertion, but finding floors or arbitrary ranges requires examining keys. Python dict preserves insertion order, not sorted order. A sorted array offers binary-search queries and shifting for insertions or deletions. A balanced BST offers individual search, update, and neighbor operations.
Java TreeMap supplies ordered-map methods such as floorKey, ceilingKey, lowerKey, higherKey, and range views. C++ offers std::map. Python's standard library has no sorted-map class. It offers bisect for sorted lists; the third-party SortedDict combines a dictionary with a sorted list of keys, so its implementation is not an AVL tree.
Key Takeaways
- Floor and ceiling include equality; successor and predecessor are strict.
- A candidate records the best valid neighbor seen along a search path.
- Range reporting prunes impossible subtrees and retains inorder output.
- Reporting keys costs , including the output work.
- A balanced tree supports order queries mixed with logarithmic updates.
- A Python dictionary preserves insertion order, which is different from sorted key order.
5.2 Store subtree sizes for rank and select
A key's rank is the number of stored keys smaller than it. Rank is defined even when the queried key is absent. Select reverses the question: select(i) returns the key at zero-based position i. Thus select(0) gives the smallest key.
Store the information needed to skip keys
Each node stores the size of its whole subtree:
In the running tree, root 50 has size 10, node 30 has size 5, node 70 has size 4, node 40 has size 3, and node 60 has size 2. Leaves have size 1. Read these stored values in constant time; recursively recounting a subtree during each query would lose the benefit.
Select a position by comparing with left size
At a node let L be its left subtree size. The node itself has local rank L. If i is smaller, go left unchanged. If equal, return the node's key. If larger, skip the left subtree and the current node, and go right with .
def subtree_size(node):
return 0 if node is None else node.size
def select(node, index):
if index < 0 or index >= subtree_size(node):
raise IndexError("rank out of range")
while node is not None:
left_size = subtree_size(node.left)
if index < left_size:
node = node.left
elif index == left_size:
return node.key
else:
index -= left_size + 1
node = node.right
For select(7), start at 50 with left size 5 and continue right with index 1. At 70, left size 2 sends you left unchanged. At 60, left size 0 sends you right with index 0. Node 65 returns 65. Select(5) returns root 50 immediately.
Accumulate a rank along the path
For rank(k), keep a total initially 0. Going left adds nothing. Going right skips every left key and the current node, so add L + 1. At equality, return the total plus L. At an empty link, return the accumulated total.
Rank(45) adds 2 at 30 and 2 at 40, giving 4. Rank(62) adds 6 at 50 and 1 at 60, then reaches an empty link with total 7. It counts 20, 30, 35, 40, 45, 50, and 60. For any stored key k, selecting its rank returns k.
For an inclusive range with lo ≤ hi, the count is rank(hi) − rank(lo), plus 1 when hi is present. From 33 through 62 it is . From 35 through 65 it is . If lo exceeds hi, return 0 before applying that formula. With 10 keys, the lower median is select(4) = 45 and the upper median is select(5) = 50.
Maintain sizes during every change
Add self.size = 1 to the node initializer for new leaves. Sizes are an augmentation, like stored heights. After an insertion or deletion, recompute them on the changed path. After a rotation, recompute the lower node before the new root. The new root's size depends on its newly positioned child. Even when an AVL insertion's balance repair stops, size changes still reach every ancestor.
A constant-time child-based update keeps balanced-tree updates at . Rank, select, and range count then take , logarithmic when balanced, instead of scanning keys in time. The same augmentation pattern can maintain a subtree sum when it too is computable from the node and its children.
Key Takeaways
- Rank counts keys strictly smaller than the query, whether or not it is stored.
- Select uses zero-based positions and the stored left subtree size.
- Going right skips the left subtree plus the current node.
- Inclusive range counts add the upper endpoint only when it is present.
- Refresh sizes on changed paths and after rotations.
- Balance controls path length; sizes let a query skip whole subtrees.
Binary Search Trees examples
1Read a tree and calculate its properties
12 steps
- 1IntroductionA hierarchy you can calculate with
A folder can contain more folders, each with its own contents. A tree records that nesting with nodes and child links. You can ask local questions, such as who a node's parent is, and whole-structure questions, such as how deep the hierarchy goes.
We will first read those relationships, then turn them into recursive calculations. Each child subtree will supply a smaller answer that its parent can combine.
- 2ExplanationStart at the root
The root has no parent; every other node has exactly one. Follow children downward and you can reach each node by one path, with no cycles.
For our example, A has children B and C. B has children D and E; E has left child G. C has right child F. B's subtree is B, D, E, G. Leaves D, G, and F have no children, while B and E are internal nodes.
- 3ExampleTrace distances along edges
Reach G along A–B–E–G. That path has three edges, so G has depth 3. To find B's height, compare its downward paths: B–D has one edge and B–E–G has two. B therefore has height 2.
Height looks for the deepest descendant leaf. D is also a leaf, but it sits at depth 2 while G sits at depth 3. A leaf need not occupy the deepest level of the whole tree.
- 4ConnectionSeparate the three shape rules
A binary tree names left and right positions, even when one is empty. Full requires zero or two children at every node. Complete fills all earlier levels and packs the last level from the left. Perfect has two children at every internal node and puts all leaves at one depth.
Our letter tree has one-child nodes E and C, so it is not full or perfect. Its last-level gaps also prevent completeness.
- 5ChallengeMeasure a new branch
Root R has left child S and right child T. S has only left child U, and T is a leaf. What are U's depth and R's height, and is the tree full?
---reveal---
U has depth 2 through R–S–U. The longest path from R also has two edges, so the height is 2. The tree is not full because S has exactly one child. T remains a leaf at the shallower depth 1.
- 6Key InsightCount links and bound height
A nonempty n-node tree has n−1 parent edges. A binary tree offers 2n child-link slots, leaving n+1 empty slots after those edges are placed.
The shape can range from a complete tree of height to a chain of height . For 10 nodes, that means 3 through 9. A perfect tree of height 3 fills four levels with 1 + 2 + 4 + 8 = 15 nodes.
- 7ExplanationRepresent empty subtrees explicitly
A general-tree node stores a value and a list of children. A binary node instead keeps a key plus
leftandrightreferences. Set a missing child toNone.This gives a recursive definition you can code directly: an empty tree is one case; a node with two subtrees is the other. Test for
Nonebefore reading attributes, so the same base case handles leaves and one-child nodes. - 8ExampleCompute one leaf first
For size, return 0 for an empty subtree and otherwise add the two child sizes plus 1. For height, return −1 for an empty subtree and otherwise add 1 to the larger child height.
A leaf gets size and height . The different base values encode different measurements: size counts nodes; height counts edges on the longest downward path.
- 9ExamplePass the answers upward
In our letter tree, D, G, and F first return height 0. E combines G's 0 with its missing right child's −1, giving height 1. B combines D's 0 and E's 1, giving 2. C gets 1 from F. A combines 2 and 1, giving tree height 3.
The size calculation follows the same dependencies but adds both child counts. B's size is 4, C's is 2, and A's is 7.
- 10ChallengeRepair an off-by-one base case
A recursive height function returns 0 for
Noneand otherwise1 + max(left_height, right_height). What does it return for a two-node chain, and what base value would make it count edges?---reveal---
It returns 1 at the leaf and 2 at the root. To count edges, return −1 for
None; the leaf then returns 0 and the root 1. The recursive step stays the same. - 11ChallengeConnect the picture to memory
A tree of 2,000 nodes is a single-child chain. A recursive size function visits every node. How do its total time and deepest active-call count compare with a balanced tree of the same size?
---reveal---
Both visit all nodes in linear time. The chain can keep about 2,000 node calls active, while a balanced tree keeps only a logarithmic-depth path. A deep chain may exceed Python's recursion limit, so an explicit stack can be needed.
- 12RecapCarry the empty case into the next algorithm
Tree vocabulary identifies which nodes belong to a path or subtree. Edge counts give depth and height, while size counts every node in the subtree. In code, an empty reference is a real case with a defined return value.
When you write the next tree algorithm, decide what a child call returns and what the parent does with that answer. The longest active path controls recursive stack use; the total number of visited nodes controls traversal work.
2Follow pending work through each traversal
20 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionChoose what must happen first
- 2ExplanationUse one tree for three orders
- 3ExampleExpand each subtree in its position
- 4ExampleWait for both children in postorder
- 5ChallengeKeep a lone child on its stated side
- 6ExplanationReplace recursive calls with a stack
- 7ExampleSave the path for inorder
- 8ChallengePredict the next stack state
- 9TipSeparate output storage from pending work
- 10ExplanationChange the waiting order with a queue
- 11ExampleFreeze a level before adding its children
- 12ChallengeFind the minimum leaf depth
- 13Key InsightWidth controls a waiting frontier
- 14ExampleBuild an expression from child results
- 15ExplanationRecord shape along with labels
- 16ExampleLocate a root in two sequences
- 17ChallengeEvaluate with the correct operand order
- 18ChallengeRebuild before choosing a traversal
- 19ConnectionReturn several related results together
- 20RecapUse dependencies to select the order
3Search and update a binary search tree
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionUse order to discard whole branches
- 2ExplanationMeet the ordered example
- 3ExampleTrace a miss to its empty link
- 4ChallengeCatch an ancestor-bound violation
- 5ExampleAttach the new leaf at the miss
- 6Key InsightSeparate ordering from shape
- 7ConnectionChoose roots from sorted data
- 8ChallengePredict the insertion endpoint
- 9ExplanationRemove a leaf and keep a child subtree
- 10ExampleFind a safe two-child replacement
- 11ExampleDelete a root whose successor has a child
- 12TipReturn the replacement at every level
- 13ChallengeKeep a successor's descendant
- 14ChallengeUse a search after both updates
- 15ConnectionAccount for the operation's path
- 16RecapCheck links as well as keys
4Repair AVL balance without losing key order
18 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionKeep tomorrow's search short
- 2ExplanationCalculate balance from child heights
- 3ExampleInspect descendants as well as the root
- 4Key InsightSee why height cannot grow freely
- 5ChallengeCheck an unequal-size pair
- 6ExplanationMove the middle subtree during a rotation
- 7ExampleStraighten a right-heavy chain
- 8ExampleRepair the zig-zag in two moves
- 9TipChoose from both factors
- 10ChallengeTrack a transferred subtree
- 11ExplanationReturn through the insertion path
- 12ExampleFollow two different insertion repairs
- 13ChallengeDistinguish a repair site from two rotations
- 14ExampleLet deletion carry a height decrease upward
- 15ExampleHandle a balanced taller child
- 16ChallengeFind the actual removal path
- 17ChallengeCombine deletion and the zero-factor case
- 18RecapRepair locally and check the affected path
5Find neighboring keys and positions
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionAsk more than whether a key exists
- 2ExplanationSeparate inclusive and strict neighbors
- 3ExamplePlace the keys before following paths
- 4ExampleImprove the floor candidate
- 5ExampleFind a successor beyond an empty right link
- 6ChallengeChoose the schedule query
- 7ExplanationPrune a range without changing sorted output
- 8ConnectionMatch costs to a workload
- 9ExplanationCount positions with left subtree sizes
- 10ExampleTrace select through changing local indices
- 11ExampleAccumulate rank instead of listing keys
- 12ChallengeAccount for an inclusive upper endpoint
- 13TipRefresh sizes even when height stops changing
- 14ChallengeCombine an update with a position query
- 15RecapKeep height, counts, and output cost distinct
Binary Search Trees practice questions
Set 1: Tree structure and visit orders10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
Show answerHide answer
Set 2: Stacks, expressions, and saved tree shapes10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
9 2 5 + - produce?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
# for every empty child. What shape is encoded by K # N L # # #?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
None and a stack holding two nodes. Should it stop or continue?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 3: Search, insertion, and deletion10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 4: AVL balance and rotations10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 5: Neighbors, ranks, and range results10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 6: Combine tree operations and diagnose errors10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
None and otherwise 1 plus the larger child height. What does it return for a single leaf?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Ancestor
Augmentation
AVL tree
B
Balance factor
Binary search tree
Binary tree
Bottom-up computation
BST invariant
C
Candidate key
Ceiling
Child
Complete binary tree
D
Degenerate tree
Depth
Depth-first traversal
Deque
deque supports popleft() without the repeated shifting needed by a list's front removal.Descendant
Double rotation
Duplicate policy
E
Empty subtree
None; recursive functions give it a direct base-case result.Explicit stack
Expression tree
(3 + 4) * (5 - 2) places multiplication above two operator subtrees.F
Floor
Full binary tree
H
Height
I
Inorder
Insertion order
Internal node
Iterative inorder
Iterator
L
Leaf
Left rotation
Left-child, right-sibling representation
Level
Level-order traversal
Lower median
M
Middle subtree
Minimum key
N
Node object
key, left, and right, with None for an absent child.O
Ordered map
P
Parent
Parent array
Perfect binary tree
Physical removal
Postfix notation
3 4 + by pushing 3 and 4 before adding them.Postorder
Predecessor
Prefix notation
* + 3 4 - 5 2 preserves the grouping of two binary operations below multiplication.Preorder
Pruning
Q
Queue
R
Range count
Range query
Rank
Rebalancing
Reconstruction
Recursion depth
Red-black tree
TreeMap uses a red-black tree to keep ordered-map operations efficient as keys change.Repair site
Right rotation
Root
Rooted tree
Rotation
S
Search path
Select
Serialization
Sibling
Sorted array
Sorted-array construction
Stored height
Subtree
Subtree replacement
Subtree size
Successor
Successor deletion
T
Traversal
Tree sort
W
Width
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.