You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: source/lectures/data/AVLtrees.md
+20-2Lines changed: 20 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -22,7 +22,7 @@ The resulting tree would be much more efficient if we were leveraging the proper
22
22
23
23
This is precisely the point of AVL trees, which are binary search trees with the additional property:
24
24
25
-
> The heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property.
25
+
> The heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, re-balancing is done to restore this property.
26
26
27
27
where
28
28
@@ -33,6 +33,25 @@ A good way of [remembering the difference](https://stackoverflow.com/q/2603692)
33
33
34
34
## Possible Implementation
35
35
36
+
The main challenge is to "re-balance" the tree when needed.
37
+
To determine if a tree needs to be re-balanced, one has to compute its "balance factor", obtained by substracting the right subtree height from the left subtree height. This is done below in the `SubtreeBalance` method.
38
+
39
+
Consider the following:
40
+
41
+
!include diag/gra/bstree_example_8.md
42
+
43
+
After inserting 2, the tree becomes:
44
+
45
+
!include diag/gra/bstree_example_10.md
46
+
47
+
which needs to be re-balanced using the `RotateleftChild` method given below. Indeed it is "left-heavy", on the left-hand side (because the left sub-tree, with root 5, is deeper, because of its left side).
48
+
49
+
If, re-using the same example, we insert 7, then the tree becomes:
50
+
51
+
!include diag/gra/bstree_example_9.md
52
+
53
+
which needs to be re-balanced using the `Doubleleftchild` method given below. Indeed it is "left-heavy", on the right-hand side (because the left sub-tree, with root 5, is deeper, because of its right side).
54
+
36
55
### Storing the height in the node
37
56
38
57
```{download="./code/projects/AVLTree.zip"}
@@ -43,4 +62,3 @@ A good way of [remembering the difference](https://stackoverflow.com/q/2603692)
43
62
44
63
It is also possible to compute the height of nodes "on the fly" instead of storing it.
45
64
[This archive](./code/projects/AVLTree_I.zip) demonstrates this concept while additionally inheriting from the `BTree` class [explored previously](./lectures/data/trees).
0 commit comments