Height and Shape

The questions in this section are about a plain binary search tree: it adds each new value as a leaf at the end of its search path and never rearranges nodes to change the tree’s shape. The height of a tree is the number of edges on the longest path from the root down to a leaf.

Solution

Each operation follows one path down from the root. Search stops when it finds the value or reaches null. Add follows the search path to the null spot and attaches a leaf there. Remove follows the search path to the node, and in the two-child case continues down the right subtree to the successor. A path down the tree has at most edges, and each step does work.

Solution

Number the levels from at the root. Level holds at most nodes, because each node has at most two children. So a tree of height holds at most

nodes. To hold nodes we need

So the smallest height is about . You get that height when every level except possibly the last is full. The largest height is , when every node except the last has exactly one child and the tree is a single path.

Solution

Order A builds a perfect tree of height :

                ╭────╮
                │ 44 │
                ╰──┬─╯
        ┌──────────┴──────────┐
     ╭──┴─╮                ╭──┴─╮
     │ 27 │                │ 68 │
     ╰──┬─╯                ╰──┬─╯
   ┌────┴────┐           ┌────┴────┐
╭──┴─╮    ╭──┴─╮      ╭──┴─╮    ╭──┴─╮
│ 15 │    │ 39 │      │ 52 │    │ 81 │
╰────╯    ╰────╯      ╰────╯    ╰────╯

Order B is sorted, so every value goes right and the tree is a single path of height :

╭────╮
│ 15 │
╰──┬─╯
   └───┐
    ╭──┴─╮
    │ 27 │
    ╰──┬─╯
       └───┐
        ╭──┴─╮
        │ 39 │
        ╰──┬─╯
           └───┐
            ╭──┴─╮
            │ 44 │
            ╰──┬─╯
               └───┐
                ╭──┴─╮
                │ 52 │
                ╰──┬─╯
                   └───┐
                    ╭──┴─╮
                    │ 68 │
                    ╰──┬─╯
                       └───┐
                        ╭──┴─╮
                        │ 81 │
                        ╰────╯

Sorted input builds a degenerate tree with height , so search, add, and remove become .