Trees and Binary Search Trees

Learn how trees store hierarchical data and how to work with them in Python. Measure depth and height, traverse a tree in preorder, inorder, postorder and level order, and use these orders to evaluate expressions and save and rebuild trees. Then search, insert and delete keys in binary search trees, keep them balanced with AVL rotations, and use them as ordered maps that answer floor, ceiling, rank and select queries in logarithmic time and report every key in a range.

IntermediateLesson 6 of 10 in Data Structures and Algorithms Course

What you will learn

  1. 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 height
      Identify 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 recursively
      Represent general and binary trees with node objects and write recursive functions for size and height that handle the empty tree correctly.
  2. 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 postorder
      Trace 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 stack
      Replace 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 queue
      Visit 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 traversals
      Use traversal orders to evaluate expression trees, save and rebuild trees, and compute properties from the bottom up.
  3. 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 property
      State 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 tree
      Add 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 tree
      Remove 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.
  4. 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 guarantees
      Compute balance factors, decide whether a tree satisfies the AVL condition and explain why that condition keeps the height logarithmic.
    • Perform single and double rotations
      Carry 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 tree
      Combine BST insertion and deletion with height updates and rotations on the way back to the root, and trace complete sequences of operations.
  5. 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 ranges
      Use 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 sizes
      Store 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.

Binary Search Trees study guide

5 chapters

1

Tree 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 n nodes, there are n−1 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 n nodes, the 2n child-link slots contain n−1 edges and n+1 empty links.

ShapeRequired structure
FullEvery node has either 0 or 2 children.
CompleteAll levels except possibly the last are filled; the last fills from the left.
PerfectEvery 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 d holds at most 2d nodes, and a perfect tree of height h has 2h+1−1 nodes.

A nonempty binary tree with n nodes has height between ⌊log⁡2n⌋ and n−1. 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 n+1 empty child links and height at most n−1.

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 1+max⁡(−1,−1)=0. Its size is 1+0+0=1. 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 n nodes, taking O(n) time. Only calls on the current downward path remain active, so the call stack takes O(h+1) space, commonly written O(h) 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 None before reading any node attribute.
  • Recursive size adds both subtree sizes; recursive height adds one to the larger height.
  • These calculations take O(n) time and stack space proportional to height.
2

Traversal 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 O(n) time. Recursion keeps O(h) pending calls for a nontrivial tree. If out stores every visited key, that output list uses another O(n) 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 n keys, so its extra result storage is O(n) 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 O(n) time. The depth-first pending stack has an O(h) 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 O(n2) 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 O(n). Queue space is O(w), where w 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 O(n) time and O(w) 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 3+4=7 and 5−2=3 before combining them as 7×3=21.

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 O(n) 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 O(n) time. Calling a fresh recursive height function at each node repeats subtree work and can take O(n2) 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.
3

Searching 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 h+1 nodes. Its time is O(h): 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 O(h).

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 O(n) 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 O(h) 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 2ln⁡n≈1.39log⁡2n 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 O(h). For sorted keys, the successive comparison counts are 0, 1, 2, and so on:

0+1+⋯+(n−1)=n(n−1)2.

For 1,000 keys, this is 499,500 comparisons. Repeated insertions take O(nlog⁡n) with short paths and O(n2) in the chain case. A later inorder traversal is only O(n); 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 O(n). Tree sort instead inserts input keys and reads inorder; balancing gives worst-case O(nlog⁡n) sorting, while a plain BST can take O(n2) 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 n(n−1)/2 comparisons.
  • Build a balanced tree from sorted keys in O(n) 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 O(h). 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.
4

AVL 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:

bf⁡(v)=h(v.left)−h(v.right).

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 N(h) be the minimum number of nodes for height h. The two child heights must be at least h−1 and h−2, giving:

N(0)=1,N(1)=2,N(h)=1+N(h−1)+N(h−2).

The counts begin 1, 2, 4, 7, 12, 20, 33, 54. They equal F(h+3)−1 for Fibonacci numbers with F(0)=0 and F(1)=1. Exponential growth of these minimum counts makes height logarithmic, with leading bound about 1.44log⁡2n. 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 O(1) 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 2log⁡2(n+1); 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.

A rotation moves a child above its parent while preserving inorder key order. It touches a constant number of links, so one rotation takes O(1) 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 T1<x<T2<y<T3. 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 zFactor at taller childRepair
+20 or +1 at left childRight rotation at z
+2−1 at left childLeft at the child, then right at z
−20 or −1 at right childLeft rotation at z
−2+1 at right childRight 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 O(log⁡n) levels. Constant work at each level keeps both AVL insertion and deletion within O(log⁡n) 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.
5

Ordered 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 m keys costs O(h+m), or O(log⁡n+m) in a balanced tree. The output itself requires work proportional to its length. Full sorted iteration is O(n).

Match the structure to the workload

A hash table gives average O(1) 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 O(log⁡n) binary-search queries and O(n) shifting for insertions or deletions. A balanced BST offers O(log⁡n) 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 m keys costs O(h+m), 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:

s(v)=1+s(v.left)+s(v.right),s(empty)=0.

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 i−L−1.

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 7−2=5. From 35 through 65 it is 7−2+1=6. 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 O(log⁡n). Rank, select, and range count then take O(h), logarithmic when balanced, instead of scanning keys in O(n) 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

5 Walkthroughs

1

Read a tree and calculate its properties

12 steps
Move from family relationships and edge counts to Python representations and recursive size and height.
  1. 1
    IntroductionA 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.

  2. 2
    ExplanationStart 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.

  3. 3
    ExampleTrace 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.

  4. 4
    ConnectionSeparate 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.

  5. 5
    ChallengeMeasure 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.

  6. 6
    Key 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 ⌊log⁡2n⌋ to a chain of height n−1. For 10 nodes, that means 3 through 9. A perfect tree of height 3 fills four levels with 1 + 2 + 4 + 8 = 15 nodes.

  7. 7
    ExplanationRepresent empty subtrees explicitly

    A general-tree node stores a value and a list of children. A binary node instead keeps a key plus left and right references. Set a missing child to None.

    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 None before reading attributes, so the same base case handles leaves and one-child nodes.

  8. 8
    ExampleCompute 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 1+0+0=1 and height 1+max⁡(−1,−1)=0. The different base values encode different measurements: size counts nodes; height counts edges on the longest downward path.

  9. 9
    ExamplePass 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.

  10. 10
    ChallengeRepair an off-by-one base case

    A recursive height function returns 0 for None and otherwise 1 + 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.

  11. 11
    ChallengeConnect 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.

  12. 12
    RecapCarry 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.

2

Follow pending work through each traversal

20 steps
Trace recursive and iterative visits, group levels with a queue, and apply traversal information to expressions and reconstruction.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionChoose what must happen first
  2. 2
    ExplanationUse one tree for three orders
  3. 3
    ExampleExpand each subtree in its position
  4. 4
    ExampleWait for both children in postorder
  5. 5
    ChallengeKeep a lone child on its stated side
  6. 6
    ExplanationReplace recursive calls with a stack
  7. 7
    ExampleSave the path for inorder
  8. 8
    ChallengePredict the next stack state
  9. 9
    TipSeparate output storage from pending work
  10. 10
    ExplanationChange the waiting order with a queue
  11. 11
    ExampleFreeze a level before adding its children
  12. 12
    ChallengeFind the minimum leaf depth
  13. 13
    Key InsightWidth controls a waiting frontier
  14. 14
    ExampleBuild an expression from child results
  15. 15
    ExplanationRecord shape along with labels
  16. 16
    ExampleLocate a root in two sequences
  17. 17
    ChallengeEvaluate with the correct operand order
  18. 18
    ChallengeRebuild before choosing a traversal
  19. 19
    ConnectionReturn several related results together
  20. 20
    RecapUse dependencies to select the order
3

Search and update a binary search tree

16 steps
Follow comparisons to insert keys and handle each deletion case, keeping every surviving subtree attached.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionUse order to discard whole branches
  2. 2
    ExplanationMeet the ordered example
  3. 3
    ExampleTrace a miss to its empty link
  4. 4
    ChallengeCatch an ancestor-bound violation
  5. 5
    ExampleAttach the new leaf at the miss
  6. 6
    Key InsightSeparate ordering from shape
  7. 7
    ConnectionChoose roots from sorted data
  8. 8
    ChallengePredict the insertion endpoint
  9. 9
    ExplanationRemove a leaf and keep a child subtree
  10. 10
    ExampleFind a safe two-child replacement
  11. 11
    ExampleDelete a root whose successor has a child
  12. 12
    TipReturn the replacement at every level
  13. 13
    ChallengeKeep a successor's descendant
  14. 14
    ChallengeUse a search after both updates
  15. 15
    ConnectionAccount for the operation's path
  16. 16
    RecapCheck links as well as keys
4

Repair AVL balance without losing key order

18 steps
Use stored heights to choose rotations, then trace insertion and deletion repairs up the affected path.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionKeep tomorrow's search short
  2. 2
    ExplanationCalculate balance from child heights
  3. 3
    ExampleInspect descendants as well as the root
  4. 4
    Key InsightSee why height cannot grow freely
  5. 5
    ChallengeCheck an unequal-size pair
  6. 6
    ExplanationMove the middle subtree during a rotation
  7. 7
    ExampleStraighten a right-heavy chain
  8. 8
    ExampleRepair the zig-zag in two moves
  9. 9
    TipChoose from both factors
  10. 10
    ChallengeTrack a transferred subtree
  11. 11
    ExplanationReturn through the insertion path
  12. 12
    ExampleFollow two different insertion repairs
  13. 13
    ChallengeDistinguish a repair site from two rotations
  14. 14
    ExampleLet deletion carry a height decrease upward
  15. 15
    ExampleHandle a balanced taller child
  16. 16
    ChallengeFind the actual removal path
  17. 17
    ChallengeCombine deletion and the zero-factor case
  18. 18
    RecapRepair locally and check the affected path
5

Find neighboring keys and positions

15 steps
Keep candidates for floor and ceiling, prune range searches, and use subtree sizes for rank and select.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionAsk more than whether a key exists
  2. 2
    ExplanationSeparate inclusive and strict neighbors
  3. 3
    ExamplePlace the keys before following paths
  4. 4
    ExampleImprove the floor candidate
  5. 5
    ExampleFind a successor beyond an empty right link
  6. 6
    ChallengeChoose the schedule query
  7. 7
    ExplanationPrune a range without changing sorted output
  8. 8
    ConnectionMatch costs to a workload
  9. 9
    ExplanationCount positions with left subtree sizes
  10. 10
    ExampleTrace select through changing local indices
  11. 11
    ExampleAccumulate rank instead of listing keys
  12. 12
    ChallengeAccount for an inclusive upper endpoint
  13. 13
    TipRefresh sizes even when height stops changing
  14. 14
    ChallengeCombine an update with a position query
  15. 15
    RecapKeep height, counts, and output cost distinct

Binary Search Trees practice questions

60 Practice Questions in 6 sets

Set 1: Tree structure and visit orders10 Practice Questions

Question 1 of 10

A rooted tree contains 13 nodes. How many edges does it contain?
  1. 13 edges
  2. 14 edges
  3. 12 edges
  4. 11 edges
Show answerHide answer
Answer: C
Every node except the root has one parent edge, so 13 nodes contribute 12 edges. Counting 13 would give the root a parent edge too, even though the root has no parent. The number of children at individual nodes does not change this total.

Question 2 of 10

Root R has left child S and right child T. S has right child U; U has left child V. T is a leaf. Using edge counts, what are T's depth and S's height?
  1. Depth 0; height 2
  2. Depth 1; height 2
  3. Depth 1; height 3
  4. Depth 2; height 1
Show answerHide answer
Answer: B
The path from R to T has one edge, so T has depth 1. The longest downward path from S is S–U–V, with two edges. A height of 3 counts the nodes on that path instead of its edges, mixing the two height conventions.

Question 3 of 10

A binary tree has a root with two children. Only the right child has children, and it has two leaves. How is this shape classified using the full, complete, and perfect definitions?
  1. Full only
  2. Complete only
  3. Full and complete
  4. Full and perfect
Show answerHide answer
Answer: A
Each node has zero or two children, so the tree is full. It is not complete because the last-level nodes sit on the right after empty left positions. It is not perfect because the left leaf is shallower than the two right-side leaves.

Question 4 of 10

A size function returns 0 for an empty subtree. A node's two child subtrees have sizes 3 and 5. What size should the node return?
  1. 8
  2. 10
  3. 6
  4. 9
Show answerHide answer
Answer: D
Combine the child sizes and include the current node: 3 + 5 + 1 gives 9. Returning 8 counts both child subtrees but omits their parent. Subtree size includes the root of the subtree being measured, even when the children already have stored results.

Question 5 of 10

Root R has left child J and right child W. J has only right child K, and W has only left child V. What is the inorder sequence?
  1. K J R V W
  2. J K R V W
  3. R J K W V
  4. J K V W R
Show answerHide answer
Answer: B
Inorder completes J's subtree as J, K, then visits R, then completes W's subtree as V, W. Placing K before J treats a right child as a left child. The empty child positions still determine where each parent appears in the sequence.

Question 6 of 10

A tree computation must total all child results before calculating the parent's result. What depth-first visit order fits this dependency?
  1. Preorder
  2. Inorder
  3. Node-right-left
  4. Postorder
Show answerHide answer
Answer: D
Postorder processes both child subtrees before their parent, so their totals are ready when the parent is calculated. Preorder would visit the parent before either child result exists. Inorder supplies only the left result before processing the parent.

Question 7 of 10

Iterative preorder has just visited root M, whose children are H and Z. It pushes H, then Z, onto a last-in, first-out stack. Which of those children is visited next, and why?
  1. Z, because it was pushed last
  2. H, because it was pushed first
  3. H, because it is the left child
  4. Z, because it is the right child
Show answerHide answer
Answer: A
The stack removes the most recently pushed item, so Z comes off next. H would come next only if it had been pushed after Z. Left-to-right preorder is achieved by the push order, not by a stack knowing which reference is a left child.

Question 8 of 10

Root M has children H and Z; H has children F and J; Z has only right child Y. What is the level-order output?
  1. M H F J Z Y
  2. F H J M Z Y
  3. M H Z F J Y
  4. F J H Y Z M
Show answerHide answer
Answer: C
The queue processes M, then H and Z, then their children F, J, and Y in that order. M H F J Z Y dives into H's branch before finishing M's level, which is preorder behavior. Newly discovered children wait behind the nodes already queued.

Question 9 of 10

Root P has children Q and R. Q has children S and T; R has no children. A level-order loop enqueues children left first. What are the tree's width and the largest number of queued nodes?
  1. Width 2; queue maximum 2
  2. Width 3; queue maximum 3
  3. Width 2; queue maximum 3
  4. Width 3; queue maximum 2
Show answerHide answer
Answer: C
The levels contain 1, 2, and 2 nodes, so width is 2. After Q is removed, the queue holds R, S, T and reaches length 3. Treating width as an exact queue limit misses the moment when the end of one level shares the queue with the start of the next.

Question 10 of 10

Distinct labels have preorder P Q S R T and inorder Q S P T R. What is the postorder sequence?
  1. S Q T R P
  2. Q S T R P
  3. S Q R T P
  4. Q S P T R
Show answerHide answer
Answer: A
P is the root, with Q/S on the left and T/R on the right. Q has right child S, while R has left child T, so their postorders are S Q and T R. Q S T R P puts the right child S before its parent in the wrong local order for that left subtree.
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

Root L has left child D and right child X. D has left child B; X has right child Z. What is the postorder sequence?
  1. B D Z X L
  2. L D B X Z
  3. B D L X Z
  4. D B X Z L
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

After iterative inorder visits node K, K has right child N, and N has left child L. What newly encountered nodes are pushed before the next visit?
  1. L, then N
  2. K, then N
  3. N, then L
  4. N only
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Why can preorder P Q alone represent two different two-node binary trees?
  1. Q may occupy P's left or right link
  2. P may occupy Q's left or right link
  3. P and Q must share one parent
  4. Q may precede P in the visit order
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

At the start of a level-order round, the queue holds three nodes. The first two have two children each, and the third has none. How many nodes belong to this round and the next round?
  1. 4 now; 3 next
  2. 3 now; 4 next
  3. 7 now; 0 next
  4. 3 now; 7 next
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What value does the postfix expression 9 2 5 + - produce?
  1. −2
  2. 2
  3. 12
  4. 16
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Preorder serialization uses # for every empty child. What shape is encoded by K # N L # # #?
  1. K has left N; N has right L
  2. K has right N; N has right L
  3. K has right N; N has left L
  4. K has left N; N has left L
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An iterative inorder traversal has current node None and a stack holding two nodes. Should it stop or continue?
  1. Stop; the current subtree is empty
  2. Stop; only child links create work
  3. Continue; restart from the original root
  4. Continue; saved nodes still need processing
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Distinct keys have preorder 42 18 27 66 53 and inorder 18 27 42 53 66. What are the right children of 18 and 42 in the reconstructed tree?
  1. 27 and 53
  2. None and 66
  3. 42 and 66
  4. 27 and 66
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

An iterative postorder method records node-right-left output, then reverses the full list. What extra-space bound includes that list?
  1. O(log⁡n)
  2. O(n)
  3. O(1)
  4. O(w)
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A balance checker calls a fresh recursive height function at every node of an n-node chain. How can it improve the worst-case running time?
  1. Return height and verdict together: O(n)
  2. Cache only the root height: O(n)
  3. Use separate subtree heights: O(log⁡n)
  4. Switch to preorder only: O(log⁡n)
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

A BST root 35 has right child 62. Node 62 has left child 47, and 47 has right child 55. What is the minimum of the subtree rooted at 62?
  1. 35
  2. 47
  3. 55
  4. 62
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A BST root has key 48. A search target is 31. Which subtree can contain it?
  1. The right subtree
  2. The left subtree
  3. Only the root
  4. Either child subtree
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A tree has root 64, left child 24, right child 91, and 24's right child 72. What makes it invalid as a distinct-key BST?
  1. 24 violates the lower bound 64
  2. 72 violates the lower bound 24
  3. 91 violates the upper bound 64
  4. 72 violates the upper bound 64
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Insert 29 into a BST with root 44, left child 16, and 16's right child 33. All unnamed child links are empty. Where is 29 attached?
  1. As the left child of 33
  2. As the right child of 16
  3. As the left child of 16
  4. As the left child of 44
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A map contains key 36 with value "old". What does putting key 36 with value "new" do under the distinct-key map policy?
  1. Add another node with that key
  2. Keep the old value unchanged
  3. Replace its value; keep one key
  4. Remove the existing key entirely
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Insert 6, 12, 18, 24, 30, 36 into an empty plain BST. Counting one key comparison per visited existing node, what are the final edge height and total build comparisons?
  1. Height 5; comparisons 15
  2. Height 6; comparisons 15
  3. Height 5; comparisons 21
  4. Height 2; comparisons 9
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A BST has root 58, right child 83, and 83's left child 71. Node 71 has right child 76. How is the link from 83 repaired when deleting 71?
  1. Set 83's left link to None
  2. Set 83's right link to 76
  3. Set 83's left link to 76
  4. Set 76's left link to 83
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A BST has root 46, left leaf 21, and right child 79. Node 79 has left child 61 and right leaf 88; node 61 has right leaf 68. After deleting 46 by successor replacement, what are the root and 79's left child?
  1. Root 79; left child 61
  2. Root 61; left child None
  3. Root 68; left child 61
  4. Root 61; left child 68
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A distinct-key BST deletes a two-child node by copying its successor's key but leaves the successor node in place. What invariant now fails?
  1. Every node has at most two children
  2. Each stored key appears once
  3. Every tree has exactly one root
  4. Every leaf has no children
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Build a BST directly from the sorted keys 4, 8, 12, 16, 20, 24, 28 by recursively choosing the middle key. Then delete the root by successor replacement. What is the new preorder?
  1. 20 8 4 12 28 24
  2. 24 8 4 12 20 28
  3. 20 8 4 12 24 28
  4. 12 8 4 24 20 28
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

A node's left subtree has height 2 and its right subtree has height 0. Using left minus right, what is its balance factor?
  1. +2
  2. −2
  3. +1
  4. 0
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Root 40 joins a left subtree that is a three-node left chain and a right subtree that is a three-node right chain. Is the whole BST AVL-balanced?
  1. Yes; the root has equal child heights
  2. No; every tree must have equal sizes
  3. No; each child root has imbalance 2
  4. Yes; every path has at most four nodes
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A subtree has root 54, left child 32, and right subtree T3. Node 32 has left subtree T1 and right subtree T2. After a right rotation at 54, where is T2?
  1. The right subtree of 32
  2. The right subtree of 54
  3. The left subtree of 32
  4. The left subtree of 54
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A node has factor −2 and its right child has factor +1. What repair restores AVL balance?
  1. Left at the child, then right at the node
  2. Right at the child, then left at the node
  3. One left rotation at the node only
  4. One right rotation at the node only
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Insert 45, 15, 30 into an empty AVL tree. Then insert 25. What are the final root and the parent of 25?
  1. Root 30; parent 45
  2. Root 30; parent 15
  3. Root 25; parent 30
  4. Root 45; parent 30
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A left rotation has moved the old root below its right child. Which affected node's stored height must be refreshed first?
  1. The new root that moved up
  2. The old parent above the rotation
  3. Any leaf in the right subtree
  4. The old root that moved down
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An AVL tree has root 52, left leaf 26, and right child 78 with leaves 65 and 91. After deleting 26, what are the new root and edge height?
  1. Root 78; height 2
  2. Root 65; height 2
  3. Root 78; height 1
  4. Root 52; height 2
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Why can a completed AVL deletion repair still require checking the repaired subtree's parent?
  1. The repaired subtree may contain new keys
  2. The repaired subtree always gains height
  3. The repaired subtree may have lost height
  4. The repaired subtree no longer obeys BST order
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Insert 8, 16, 24, 32, 40 into an empty AVL tree, then delete 8. What is the resulting preorder?
  1. 16 32 24 40
  2. 24 16 32 40
  3. 32 24 16 40
  4. 32 16 24 40
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

The fewest-node AVL counts begin N(0)=1 and N(1)=2. How many nodes are needed for edge height 4, and can an 11-node AVL tree have that height?
  1. 12 nodes; it cannot
  2. 11 nodes; it can
  3. 12 nodes; it can
  4. 7 nodes; it can
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

An ordered map stores keys 11, 23, 34, 58, 76. What is floor(41)?
  1. 23
  2. 41
  3. 58
  4. 34
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Event keys are 105, 120, 155, 190. A request asks for the first event at or after 120, and another asks for the first strictly after 120. What do they return?
  1. 120 and 120
  2. 120 and 155
  3. 155 and 155
  4. 105 and 155
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Stored keys are 3, 14, 22, 39, 57, 81. What are rank(40) and select(4), using zero-based select?
  1. 4 and 57
  2. 3 and 39
  3. 4 and 39
  4. 5 and 57
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A BST has root 41, left child 19, and right child 73. Node 19 has right child 28, which has right child 36. What is the successor of 36?
  1. 28
  2. 36
  3. 41
  4. 73
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

For an inclusive range 26 through 64, a traversal is at BST node 26. Which child subtrees can it skip without inspecting their keys?
  1. Skip right; still consider left
  2. Skip both child subtrees
  3. Skip left; still consider right
  4. Skip neither child subtree
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A size-augmented BST has root 37, left subtree of size 3, and right child 68. Node 68 has left child 49, whose right child is 56; 68's right child is 84. What does select(5) return?
  1. 56
  2. 49
  3. 68
  4. 84
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An ordered map stores 9, 17, 28, 43, 59, 74, 88. Delete 28, then insert 52. How many stored keys are in the inclusive range 17 through 74, and what is their zero-based select(3) in the whole map?
  1. 4 keys; select(3) is 52
  2. 5 keys; select(3) is 43
  3. 4 keys; select(3) is 43
  4. 5 keys; select(3) is 52
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

An ordered map has rank(25)=2 and rank(70)=8; key 70 is stored. After deleting one key below 25 and inserting one new key strictly between 25 and 70, what is the inclusive count from 25 through 70?
  1. 6
  2. 8
  3. 7
  4. 9
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A size-augmented AVL subtree has root 60, left child 24 with children 12 and 42, and right leaf 90. After a right rotation at 60, what are the new sizes at 60 and 24?
  1. Size(60)=2; size(24)=5
  2. Size(60)=3; size(24)=5
  3. Size(60)=3; size(24)=4
  4. Size(60)=5; size(24)=3
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A balanced catalog starts with n keys and performs n insertions, then n floor queries. It then reports n inclusive ranges, each containing n/2 keys. What are the total time bounds for the insertion phase, the floor phase, and the range phase?
  1. O(nlog⁡n), O(nlog⁡n), O(nlog⁡n)
  2. O(n2), O(nlog⁡n), O(n2)
  3. O(n), O(n2), O(n2)
  4. O(nlog⁡n), O(nlog⁡n), O(n2)
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

A height function returns 0 for None and otherwise 1 plus the larger child height. What does it return for a single leaf?
  1. −1
  2. 1
  3. 0
  4. 2
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A lazy inorder iterator yields keys from a BST with root 31, left child 13 with right child 22, and right leaf 48. After yielding 13 and 22, what key is yielded next?
  1. 13
  2. 22
  3. 31
  4. 48
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Distinct nodes have preorder 38 14 29 63 47 72 and inorder 14 29 38 47 63 72. Rebuild the tree. What is the unsuccessful search path for 50, including its final empty link?
  1. 38, 63, 47, empty right
  2. 38, 63, 47, empty left
  3. 38, 14, 29, empty right
  4. 38, 63, 72, empty left
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A BST has root 57, left child 25 with children 10 and 39, and right child 82 with left child 69. Node 69 has right child 74. Delete 57 by successor replacement, then delete 25 the same way. What is the resulting preorder?
  1. 69 39 10 74 82
  2. 74 39 10 82 69
  3. 69 10 39 82 74
  4. 69 39 10 82 74
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Insert 70, 30, 50, 90, 80 into an empty AVL tree. What is the final preorder?
  1. 70 30 50 90 80
  2. 50 30 70 90 80
  3. 70 50 30 80 90
  4. 50 30 80 70 90
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A node has factor +2 and its left child has factor 0 after deletion. What rotation is needed?
  1. One left rotation at the node
  2. One right rotation at the node
  3. Left at child, then right at node
  4. Right at child, then left at node
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A size-augmented AVL tree has root 44, left child 22 with leaves 11/33, and right child 77 with leaves 66/88. Insert 27, initializing its size to 1 but leaving all old size fields unchanged. Links remain AVL-balanced. What does the usual size-based rank(70) return, and what is the correct rank?
  1. 5; correct rank 6
  2. 6; correct rank 6
  3. 5; correct rank 5
  4. 6; correct rank 5
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A BST has root 43, left child 16 with right child 31, and right child 77 with left child 59. Delete 43 by successor replacement. What are floor(60), successor(31), and the inclusive range 30 through 60?
  1. 59; 43; [31, 43, 59]
  2. 31; 59; [31, 59]
  3. 59; 59; [31, 59]
  4. 59; 77; [31, 59]
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A map stores 7, 19, 33, 48, 62, 79, 95. Insert 55, delete 19, then delete the current lower median. What is the final inclusive count from 33 through 79?
  1. 4
  2. 3
  3. 5
  4. 6
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An augmented AVL tree repeatedly recomputes every child subtree's height by a fresh recursive scan while repairing one update. Which implementation change restores constant work per local height check?
  1. Replace recursion with a queue scan
  2. Read and refresh stored child heights
  3. Recompute heights from the root first
  4. Use subtree sizes in place of heights
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

78 Key Terms, each with its definition

A

Ancestor
An ancestor is a node on the path from a node's parent toward the root, including the root for a nonroot node.
If the path is A, B, E, G, the ancestors of G are E, B, and A.
Augmentation
An augmentation stores extra subtree information at each node, computable from that node and its children for efficient maintenance.
A subtree-sum augmentation can be refreshed on the changed path alongside stored heights and sizes.
AVL tree
An AVL tree is a BST whose two child-subtree heights differ by at most 1 at every node, keeping overall height logarithmic.
An AVL tree can have leaves at different depths and unequal subtree sizes while obeying every local height check.

B

Balance factor
A balance factor is the left subtree height minus the right subtree height here, with −1 used for an empty child subtree.
A balance factor of +2 identifies a left-heavy node needing repair after an AVL update.
Binary search tree
A binary search tree orders each node's entire left subtree below its key and its entire right subtree above it, for distinct keys.
A binary search tree rejects 60 anywhere in the left subtree of 50, even as the right child of 30.
Binary tree
A binary tree is empty or consists of a node with at most two children, each assigned a distinct left or right position.
A lone left child and a lone right child define different binary tree shapes.
Bottom-up computation
A bottom-up computation combines child results at a parent after the children have been processed, following postorder dependencies.
A bottom-up computation returns both height and a balance verdict so no subtree needs a separate height scan.
BST invariant
The BST invariant is the ordering rule that every descendant must obey relative to its ancestors, maintained through all operations.
A parent-only check can miss a violated BST invariant when a deep key crosses an ancestor's allowed bound.

C

Candidate key
A candidate key is the best valid answer retained so far while a floor, ceiling, or neighbor search checks for a closer key.
A floor search for 62 replaces candidate key 50 by 60 before rejecting 65 as too large.
Ceiling
The ceiling of a query key is the smallest stored key greater than or equal to it; it is absent when every stored key is smaller.
A schedule uses ceiling to find an event at or after a requested time, allowing an exact match.
Child
A child is a node directly below its parent, connected by one edge; a binary child occupies a left or right position.
A node with only a right child still has an empty left position in a binary-tree representation.
Complete binary tree
A complete binary tree fills every level before the last and places any last-level nodes consecutively from the left.
A last-level gap before an existing node makes a binary tree incomplete, even if its height is small.

D

Degenerate tree
A degenerate tree has become chain-shaped, giving height linear in node count and making a worst-case search visit every node.
Five increasing keys inserted into a plain BST produce a degenerate tree of edge height 4.
Depth
The depth of a node is the number of edges on its unique path from the tree's root; the root has depth 0.
G has depth 3 when reaching it follows the three edges A–B, B–E, and E–G.
Depth-first traversal
A depth-first traversal explores a subtree fully before moving to the next subtree, using recursion or an explicit stack.
A depth-first traversal can reach a deep node in one branch before returning to explore the next branch.
Deque
A deque is a double-ended collection with constant-time additions and removals at either end, suited to a level-order queue.
Python's deque supports popleft() without the repeated shifting needed by a list's front removal.
Descendant
A descendant is a node below another node, reachable by following one or more child links from that other node.
G is a descendant of B when the downward path from B passes through E before reaching G.
Double rotation
A double rotation performs two linked rotations to repair a left-right or right-left zig-zag by lifting the middle key.
A double rotation for 30, 25, 28 lifts 28 above both 25 and 30 in the repaired subtree.
Duplicate policy
A duplicate policy states how repeated keys are handled, such as replacing a map value or increasing a stored occurrence count.
A map's duplicate policy updates the old value without creating a second node for the same key.

E

Empty subtree
An empty subtree contains no nodes and is represented by None; recursive functions give it a direct base-case result.
An empty subtree contributes size 0 and height −1 to the calculation at its parent.
Explicit stack
An explicit stack is a program-managed last-in, first-out collection that stores the pending work otherwise held by recursive calls.
An explicit stack for preorder holds the right child below the left child so the left branch runs next.
Expression tree
An expression tree stores operands in leaves and operators in internal nodes, with subtree positions defining operand grouping.
The expression tree for (3 + 4) * (5 - 2) places multiplication above two operator subtrees.

F

Floor
The floor of a query key is the greatest stored key less than or equal to it; it is absent when every stored key is larger.
When 60 is the largest stored key below 62, the floor of 62 is 60, while the floor of stored key 40 is 40 itself.
Full binary tree
A full binary tree has either zero or two children at every node; a node with exactly one child breaks the rule.
A root with two leaf children is full, while extending just one leaf with one child makes it nonfull.

H

Height
The height of a node is the number of edges on its longest downward path to a leaf; the empty-tree height is −1 here.
B has height 2 when its longest downward path is B–E–G, although D is only one edge away.

I

Inorder
Inorder visits the left subtree, then the current node, then the right subtree; on a distinct-key BST it produces increasing keys.
Inorder visits G before E when G is E's left child, even if E has no right child.
Insertion order
The insertion order is the sequence in which keys arrive; in a plain BST it determines which nodes become ancestors of later keys.
Increasing insertion order creates a right chain, while choosing a middle key first can shorten paths.
Internal node
An internal node has at least one child; unlike a leaf, it has a nonempty downward continuation in the tree.
C is an internal node when it has right child F, even though its left child link is empty.
Iterative inorder
Iterative inorder saves a leftward path on a stack, visits a popped node, and then continues into that node's right subtree.
Iterative inorder can pause after the third BST key without first collecting the whole sorted output.
Iterator
An iterator produces items one at a time while keeping enough state to resume, such as a current node and pending stack.
A tree iterator can yield the next key while preserving the remaining left-path stack for a later call.

L

Leaf
A leaf is a node with no children, so its downward path ends immediately and its edge-counting height is 0.
A childless node D remains a leaf even when another branch reaches a deeper node G.
Left rotation
A left rotation lifts a node's right child, moves the old root down to the left, and transfers the middle subtree to the old root.
A left rotation repairs the right-right chain 10, 20, 30 by lifting 20 to its top.
Left-child, right-sibling representation
A left-child, right-sibling representation stores a general tree using one link to the first child and one to the next sibling.
In a left-child, right-sibling representation, following right links lists siblings instead of ordinary right descendants.
Level
A level is the group of all nodes at one depth, measured from the root at level 0 in the edge-counting convention.
D, E, and F share level 2 when each is two edges below root A.
Level-order traversal
A level-order traversal visits nodes by increasing depth and left to right within a level, using a first-in, first-out queue.
When B and C are children of the root, level-order traversal processes both before any of their children D, E, or F.
Lower median
The lower median is the middle key for odd size or the lower of the two middle keys for even size, selected by zero-based rank.
For 10 sorted keys, the lower median is at index 4; the upper middle key is at index 5.

M

Middle subtree
The middle subtree holds keys between the two nodes involved in a single rotation and must transfer to the correct new child link.
During a right rotation, the middle subtree moves from the rising node's right to the falling node's left.
Minimum key
The minimum key is the smallest stored key; in a nonempty BST it is found by following left links until no left child remains.
The minimum key in a subtree rooted at 60 can be 60 even when 60 has right child 65.

N

Node object
A node object holds one tree item and references to its children, allowing algorithms to follow the hierarchy through links.
A Python node object can store key, left, and right, with None for an absent child.

O

Ordered map
An ordered map stores distinct key-value pairs and supports queries based on key order alongside lookup, insertion, and deletion.
An ordered map can find the next scheduled key while accepting new entries between existing ones.

P

Parent
A parent is the node directly above another node, joined to it by one edge in the direction toward the root.
If B links directly to child E, B is E's parent even when E has descendants of its own.
Parent array
A parent array stores each numbered node's parent number, using a special marker for the root that has no parent.
A parent array entry of −1 can identify the root, while another entry records that node 4 belongs to node 1.
Perfect binary tree
A perfect binary tree has two children at every internal node and all its leaves at the same depth.
A perfect binary tree of height 3 has 15 nodes, including 8 leaves on its deepest level.
Physical removal
The physical removal is the unlinking of the actual node object during deletion, which may differ from the node whose key is replaced.
A two-child deletion starts height repairs along the physical removal path of the successor.
Postfix notation
Postfix notation writes an operator after its operands; postorder of an expression tree produces this form.
A stack evaluator reads postfix notation 3 4 + by pushing 3 and 4 before adding them.
Postorder
Postorder completes the left subtree and then the right subtree before visiting their parent, making child results available first.
Postorder supplies the totals of two subfolders before calculating the total at their containing folder.
Predecessor
A predecessor is the greatest stored key strictly smaller than a given key; for a node with a left subtree it is that subtree's maximum.
When 50 is the largest stored key below 60, the predecessor of 60 is 50, while the predecessor of the minimum is absent.
Prefix notation
Prefix notation writes an operator before its operands; preorder of an expression tree produces this form.
The prefix notation * + 3 4 - 5 2 preserves the grouping of two binary operations below multiplication.
Preorder
Preorder visits the current node before its left and right subtrees, completing the left subtree before the right.
Preorder begins A, B, D when A has left child B and B has left leaf D.
Pruning
Pruning skips a subtree when the BST bounds prove none of its keys can contribute to the current query.
Pruning avoids the left subtree when its root key is already no greater than the range's lower bound.

Q

Queue
A queue removes the earliest added item first; tree level order adds children behind all nodes already waiting.
After visiting B, a level-order queue can hold C, D, E, with C still scheduled to leave first.

R

Range count
A range count gives how many keys lie within bounds without listing them, using ranks and an upper-endpoint membership adjustment.
An inclusive range count from 35 through 65 adds 1 because the upper endpoint 65 is stored.
Range query
A range query reports keys within stated bounds; an inclusive BST range walk prunes impossible subtrees while keeping inorder output.
If the stored keys between 33 and 62 are 35, 40, 45, 50, and 60, a range query from 33 through 62 reports them in sorted order.
Rank
The rank of a key is the number of stored keys strictly smaller than it, whether or not the queried key is present.
The rank of absent key 62 is 7 when seven stored keys lie below it in the map.
Rebalancing
Rebalancing repairs an AVL node with height difference 2 using a single or double rotation selected from its child's balance factor.
Rebalancing after deletion can continue upward because the repaired subtree may become shorter.
Reconstruction
Reconstruction builds a tree from saved information, such as preorder with empty markers or two suitable traversal sequences.
With distinct keys, reconstruction splits inorder around the first preorder key to identify the two subtrees.
Recursion depth
The recursion depth is the number of nested active calls; a recursive tree calculation reaches depth proportional to tree height.
A chain creates large recursion depth because each call waits for the next single-child subtree.
Red-black tree
A red-black tree is a balanced BST using color rules to guarantee logarithmic height and worst-case logarithmic search and updates.
Java TreeMap uses a red-black tree to keep ordered-map operations efficient as keys change.
Repair site
A repair site is an unbalanced ancestor where one single or double rotation restores local AVL balance during an update.
One AVL insertion needs at most one repair site, even when that site takes two primitive rotations.
Right rotation
A right rotation lifts a node's left child, moves the old root down to the right, and transfers the middle subtree to the old root.
A right rotation at y with left child x makes x's former right subtree the new left subtree of y.
Root
The root is the tree's starting node, with no parent; every other node is reached by following links downward from it.
In a tree with A above B and C, A is the root and both child paths begin there.
Rooted tree
A rooted tree is a connected hierarchy with one root, exactly one parent for every other node, and no cycles.
A folder hierarchy forms a rooted tree when every file or subfolder has one containing folder.
Rotation
A rotation changes a constant number of parent-child links and the local subtree root while preserving the inorder key sequence.
A rotation can lift 20 above 10 without changing the sorted sequence 10, 20, 30.

S

Search path
A search path is the sequence of nodes examined as comparisons choose a single child until a key is found or an empty link is reached.
The search path for 62 can be 50, 70, 60, 65 before ending at an empty left link.
Select
Select returns the key at a specified zero-based rank, using left-subtree sizes to decide which group contains that position.
Select at index 7 returns 65 when 65 is the map's eighth-smallest stored key.
Serialization
Serialization converts a tree into stored data; preserving an arbitrary binary shape requires recording missing child positions too.
Preorder serialization distinguishes A with left child B from A with right child B by its empty-link markers.
Sibling
A sibling is another node with the same parent; siblings need not have the same number of children or subtree height.
D and E are siblings when both are children of B, even if only E has a child.
Sorted array
A sorted array keeps keys in order for binary search, but inserting or deleting an element can require shifting linearly many entries.
A sorted array suits order queries on data that rarely changes, because updates incur shifts.
Sorted-array construction
Sorted-array construction builds a balanced BST by choosing a middle key as root and recursively building its two index ranges.
Sorted-array construction turns seven sorted keys into a height-2 tree without repeated search-based insertion.
Stored height
A stored height is a node field recording subtree height, refreshed from the child fields so a balance check takes constant time.
A stored height must change after links move, even when the node's key stays the same.
Subtree
A subtree consists of a chosen node as its root together with every descendant and the links joining those nodes.
When B has children D and E and E links to G, the subtree rooted at B includes B, D, E, and G.
Subtree replacement
A subtree replacement reconnects a parent to the root returned by an update, including an empty root or a promoted child.
Subtree replacement lets the same recursive deletion handle an internal node and the whole tree's root.
Subtree size
The subtree size is the number of nodes in a subtree, including its root; it is 1 plus the two binary-child sizes.
A subtree size of 4 can count B itself together with descendants D, E, and G.
Successor
A successor is the smallest stored key strictly greater than a given key, unlike ceiling which permits an exact match.
When 50 is the next stored key above 45, the successor of 45 is 50 even if 45 has no right subtree and an ancestor supplies the result.
Successor deletion
Successor deletion removes a two-child node's key by replacing it with the right subtree's minimum, then deleting that old occurrence.
When 60 is the minimum of root 50's right subtree, successor deletion at 50 copies 60 and reconnects 60's right child 65 in its old position.

T

Traversal
A traversal processes every node once in a specified order; processing may print a key, collect it, or compute a result.
A traversal that collects labels must distinguish entering a recursive call from actually visiting its node.
Tree sort
Tree sort builds a search tree from input keys and then lists them with inorder traversal, with cost determined by construction.
Tree sort using a balanced tree keeps worst-case time logarithmic per insertion before its final linear walk.

W

Width
The width of a tree is its largest number of nodes at one level; it controls the asymptotic queue space of level order.
A perfect 15-node tree has width 8 because its deepest level contains eight leaves.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started