Skip to content

Binary search tree

storing

Level 2 of 3

Also called Sorted binary tree.

fresh numbers

The test's questions that a run answers, asked again on new numbers whenever you like. The answer, its working and the reason for every other choice come from binary search tree's own run on the numbers shown.

choose one

question 1

An empty tree puts in 50, 30, 70, 20, 40 and 60, in that order. How many comparisons do the six puts make in all?

the answer, and why

the answer is D

50 is the top, 0. 30 and 70 meet 50, 1 each. 20 and 40 meet 50 and 30, 2 each. 60 meets 50 and 70, 2. That is 8.

  1. step 17 of 21

    2030405070

    To put 60 in, start at the top.

    numbers compared: 0

  2. step 18 of 21

    2030405070

    60 is bigger than 50, so go right.

    numbers compared: 1

  3. step 19 of 21

    2030405070

    60 is smaller than 70, so go left.

    numbers compared: 2

  4. step 20 of 21

    203040506070

    The way runs out, so hang 60 to the left of 70.

    numbers compared: 2

Operation 6 puts 60 in. It meets 50, then 70, and hangs to the left of 70. 2 comparisons.

if you chose another

  • That counts every number before each put, as if the tree were a path.
  • That counts 1 comparison a put after the first, but 20, 40 and 60 hang on level 2.
  • That counts only the last three puts.

new numbers

question 2

Which order of these seven numbers, put into an empty tree, costs the fewest comparisons?

the answer, and why

the answer is B

45 is the middle, then 25 and 65 are the middles of each side. 45 costs 0, 25 and 65 cost 1 each, and the 4 numbers on level 2 cost 2 each, 8. That is 10.

if you chose another

  • In order, each number meets all before it, a path, 21.
  • 45 is the middle, but each side goes in order, a path on each side, 12.
  • 25 is not the middle, so the tree leans right, 12.

new numbers

question 3

An empty tree puts in 30, 10, 50, 40 and 60, then takes 30 out. How many comparisons do the six operations make?

the answer, and why

the answer is D

The puts make 0, 1, 1, 2 and 2, which is 6. The take meets 30 at the top, 1. 40, the smallest number to its right, takes its place, reached by following links with no comparison. That is 7.

  1. step 18 of 24

    1030405060

    Here is 30.

    numbers compared: 1

  2. step 20 of 24

    1030405060

    Go right once, to 50.

    numbers compared: 1

  3. step 21 of 24

    1030405060

    Go left, to 40.

    numbers compared: 1

  4. step 23 of 24

    10405060

    40 moves up to where 30 was, and 30 is out.

    numbers compared: 1

Operation 6 takes 30 out. It is met at the top. Then the walk goes right to 50 and left to 40, and 40 moves up to where 30 was.

if you chose another

  • That leaves out the take's comparison with 30.
  • That counts the walk to 50 and 40 as 2 comparisons; it only follows links.
  • That counts the walk to 40 as 1 comparison; it only follows links.

new numbers