14 11 17 7 53 4 - University of Cyprus treeSolutions.pdf · ΕΠΛ 231 – Δομές...

Post on 06-Sep-2018

229 views 0 download

Transcript of 14 11 17 7 53 4 - University of Cyprus treeSolutions.pdf · ΕΠΛ 231 – Δομές...

AVL Tree Example:

• Insert 14, 17, 11, 7, 53, 4, 13 into an empty AVL tree

14

17 11

7 53

4

ΕΠΛ 231 – Δομές Δεδομένων και Αλγόριθμοι

Φροντιστήριο 7

1. Ξεκινώντας με ένα άδειο AVL-δένδρο να εφαρμόσετε διαδοχικά εισαγωγή των στοιχείων

2, 1, 4, 5, 9, 3, 6, 7, 16, 0 δείχνοντας το αποτέλεσμα της κάθε μιας από τις εισαγωγές.

AVL Tree Example:

• Insert 14, 17, 11, 7, 53, 4, 13 into an empty AVL tree

14

17 7

4 53 11

13

AVL Tree Example:

• Now insert 12

14

17 7

4 53 11

13

12

AVL Tree Example:

• Now insert 12

14

17 7

4 53 11

12

13

AVL Tree Example:

• Now the AVL tree is balanced.

14

17 7

4 53 12

13 11

AVL Tree Example:

• Now insert 8

14

17 7

4 53 12

13 11

8

AVL Tree Example:

• Now insert 8

14

17 7

4 53 11

12 8

13

AVL Tree Example:

• Now the AVL tree is balanced.

14

17

7

4

53

11

12

8 13

AVL Tree Example:

• Now remove 53

14

17

7

4

53

11

12

8 13

AVL Tree Example:

• Now remove 53, unbalanced

14

17

7

4

11

12

8 13

AVL Tree Example:

• Balanced! Remove 11

14

17

7

4

11

12 8

13

AVL Tree Example:

• Remove 11, replace it with the largest in its left branch

14

17

7

4

8

12

13

AVL Tree Example:

• Remove 8, unbalanced

14

17

4

7

12

13

AVL Tree Example:

• Remove 8, unbalanced

14

17

4

7

12

13

AVL Tree Example:

• Balanced!!

14

17 4

7

12

13

In Class Exercises

• Build an AVL tree with the following values:

15, 20, 24, 10, 13, 7, 30, 36, 25

15

15, 20, 24, 10, 13, 7, 30, 36, 25

20

24

15

20

24

10

13

15

20

24

13

10

13

20

24

15 10

13

20

24

15 10

15, 20, 24, 10, 13, 7, 30, 36, 25

7

13

20

24 15

10

7

30

36 13

20

30 15

10

7

36 24

13

20

30 15

10

7

36 24

15, 20, 24, 10, 13, 7, 30, 36, 25

25

13

20

30

15

10

7

36

24

25 13

24

36

20

10

7

25

30

15

Remove 24 and 20 from the AVL tree.

13

24

36

20

10

7

25

30

15

13

20

36

15

10

7

25

30

13

15

36

10

7

25

30

13

30

36

10

7

25

15

Question 2 (a) Insert the following sequence of elements into an AVL tree, starting with an empty

tree: 10, 20, 15, 25, 30, 16, 18, 19.

(b) Delete 30 in the AVL tree that you got.

Solution: (a) Red dashed line signifies first part of double rotate action.

(b).

10

25 15

30

20

18

16 19 10

25

15

20

18

16

19 10 25

15 20

18

16 19

20

10

15

15

10

20

10 20

15

25

30

10 25

15

30 20

16

10

25

15

30

20

16 10

25 15

30

20

16

18

19

10

25 15

30

20

18

16 19