Binary Search Trees

advertisement

Find 13:

6

2 9

7 13

Find

15

11

16

20

18 23

Find Min:

6

Find Min and Find Max

15

Find Max:

16

20

2 9

7 13

18 23

11

Insert 13:

5

2 9

Insert

12

15

18

19

17

Insert 13:

5

2 9

Insert

12

15

18

19

13 17

Delete 13:

5

2 12

Delete

15

10 13

6

7

16

20

18 23

Delete 13:

5

2 12

Delete

15

6

10

16

20

18

• No child (leaf)

• Deleted directly

23

7

Delete 16:

5

2 12

Delete

15

10 13

6

7

16

20

18 23

Delete 16:

5

2 12

Delete

15

6

10 13

16

20

18

• 1 child

• Splice out node

23

7

Delete 16:

5

2 12

Delete

15

10 13

6

7

18

20

23

• tree re-drawn for proper level layout

Delete 5:

5

2 12

Delete

15

10 13

6

7

16

20

18 23

Delete 5:

5

2 12

Delete

15

6

10

7

13

16

20

18

• 2 children

• Splice out min node of right sub-tree

23

Delete 5:

5

2 12

Delete

15

6 7

10 13

16

20

18 23

• Orphaned node’s key needs to replace key in node to be deleted

Delete 5:

6

2 12

Delete

15

10 13

7

16

20

18 23

The Effect of the Input Sequence on the Shape of BSTs

• The order in which keys arrive and are inserted impacts the shape of the resulting tree

• The shape of the tree determines performance

• All input sequences need to be accommodated in a well behaving BST data structure

• Deletions also affect tree shape (performance)

Unbalanced BST

Insert the numbers 1, 2, 3, 4, 5, 6, 7 into empty BST:

1

2

2

3

4

5

6

• Input sequence degenerated the tree into a linked list (linear) data structure.

7

Unbalanced BST

Insert the numbers 7, 6, 5, 4, 3, 2, 1 into empty BST:

7

6

5

4

3

2

1

• Tree is linear again.

Unbalanced BST

Insert the numbers 4, 3, 5, 2, 6, 1, 7 into empty BST:

4

5 3

6

2

7

1

• Tree is still very unbalanced (near-linear).

Unbalanced BST

Insert the numbers 1, 3, 2, 5, 4, 7, 6, 8 into empty BST:

1

3

2

5

4 7

6

8

• Tree is still very unbalanced (height is linear).

Balanced BST

Insert the numbers 4, 2, 6, 1, 3, 5, 7 into empty BST:

4

2 6

1

3 5

7

• Tree is “dense” with a low height.

Download