Skip to content

Commit 719238d

Browse files
ClémentClément
authored andcommitted
Adding solution for problem 4 of exam 2
1 parent d2c7672 commit 719238d

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
%%%
2+
3+
A((13))-->B((8))
4+
A-->C((15))
5+
B~~~H1:::hidden
6+
B-->D((9))
7+
C~~~H2:::hidden
8+
C-->F((25))

source/solutions/data/trees.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,60 @@ tags:
6868
- Postorder gives 6, 14, 12, 13, 10
6969
</details>
7070

71+
72+
#. Consider the following AVL tree:
73+
74+
!include diag/gra/bstree_example_11.md
75+
76+
#. Give its *inorder* traversal.
77+
78+
<details>
79+
<summary>Solution</summary>
80+
8, 9, 10, 13, 15, 25
81+
</details>
82+
83+
#. Give an order in which the values could have been inserted (for example, even if this is incorrect, "9, 13, 25, …") to obtain this tree.
84+
85+
<details>
86+
<summary>Solution</summary>
87+
The values could have been inserted as
88+
89+
- 10, 8, 15, 9, 13, 25
90+
- 10, 15, 8, 9, 13, 25 (permuting 15 and 8),
91+
- 10, 8, 15, 13, 25, 9 (permuting 13, 25, and 9),
92+
93+
or some other variations: the important aspects are:
94+
95+
1. Start with 10,
96+
2. Do not, while inserting the tree, make it un-balanced (otherwise, the tree would re-balance itself and 10 would not be the root).
97+
98+
If one wants to leverage re-balancing of the tree, then we can use the following sequence:
99+
100+
- 15, 13, 25, 10, 8, 9
101+
102+
Indeed, the tree remains balanced until 9 is inserted: inserting 9 triggers a re-balancing that actually produce the tree given as an example.
103+
An example of an **incorrect** sequence could be
104+
105+
- 15, 13, 8, 9, 25, 10,
106+
107+
as this produces a tree with 13 at its root.
108+
</details>
109+
110+
#. Draw next to the drawing the tree obtained after 10 was removed.
111+
112+
<details>
113+
<summary>Solution</summary>
114+
There are two strategies after the root was removed:
115+
116+
- Replacing it with the greatest value on the sub-tree to the left,
117+
- Replacing it with the lowest value on the sub-tree to the right.
118+
119+
The second strategy, which is the one [implemented in the lecture notes](./lectures/data/AVLtrees), gives:
120+
121+
!include diag/gra/bstree_example_12.md
122+
123+
</details>
124+
71125
#. Consider the following implementation of "random" binary trees:
72126

73127
```

0 commit comments

Comments
 (0)