Skip to content

Commit 80cdea9

Browse files
committed
Heaps and red black tree notes.
1 parent 393906f commit 80cdea9

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

5-trees/HeapNotes.md

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
### Heaps
2+
Heaps are unlike binary trees in that they don't have to have 2 children.
3+
4+
The topmost node (root node) must be either the biggest or the smallest, and then going from left to right in each level, the numbers must descend or ascend appropriately (monotonicity?). Min heap has the root being the smallest and max heap has the root being the biggest.
5+
6+
They must also be complete, so L to R until filled (don't have to be perfect trees but cannot fill in the right if the left is not done).
7+
8+
Peeking looks at the top node which is either the largest or the smallest so it takes O(1) time.
9+
10+
Worst case search takes O(n) if what you want is at the end, and average case takes O(n/2) because if you hit a value that is smaller than your searched-for number in a max heap you know you can stop.
11+
12+
### Heapify
13+
14+
Generally when you insert into a heap, convention is to stick the element in the bottom most open leaf and then heapify, which means to sort it properly.
15+
16+
Extracting works similarly--if you remove the root, then you just take the last one and stick it up top then heapify.
17+
18+
Heaps can be stored in arrays because one knows that for a heap with two children per node, the array index increases by powers of 2.
19+
20+
ex:
21+
22+
Levels: 1 2 2 3 3 3 3

5-trees/RedBlackTreesNotes.md

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
### Red Black Trees
2+
3+
Example of a self-balancing tree. Red black trees are a type of BST (binary search tree) with extra rules.
4+
5+
1. Root node must be black (sometimes optional rule)
6+
2. If a node is red, its two children must be black
7+
3. There exist null leaf nodes that are always black
8+
4. Every path in this tree must have the same # of black nodes.
9+
10+
Generally, nodes are inserted as red nodes.
11+
12+
### Tree Rotation
13+
14+
When a parent P of an inserted red node is red while P's sibling is black, one must perform a tree rotation.
15+
16+
(I'm not adding in the null black nodes for this diagram)
17+
18+
9b
19+
/ \
20+
6b 19b
21+
/ \
22+
13r 16r
23+
24+
In the example-- left rotation.
25+
26+
9b
27+
/ \
28+
6b 19b
29+
/
30+
16r
31+
/
32+
13r
33+
34+
And we still have to follow the rules of the BST! So while we balance the tree we keep that in mind. Hence we need...a right rotation in order to balance the tree:
35+
36+
37+
9b
38+
/ \
39+
6b 16b <--- this got turned black
40+
/ \
41+
13r 19r
42+
43+
44+
Gosh, I wish there were more finger exercises for this section.
45+
46+

0 commit comments

Comments
 (0)