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
Trees are like linked lists except they can have more than one next.
4
+
5
+
- Trees must be completely connected
6
+
- Trees must not have cycles
7
+
8
+
The level of a tree starts counting at 1 from the root node.
9
+
The height of a tree starts counting from the leaf nodes as 0, upwards.
10
+
The depth of a tree is the number of edges (connections), which starts at 0 from the root node.
11
+
12
+
Identical terms:
13
+
- Parent/Child
14
+
- Ancestor/Descendent
15
+
- Internal/Leaf
16
+
17
+
### Quiz
18
+
19
+
a
20
+
/ \
21
+
b c
22
+
/ /
23
+
d e
24
+
\
25
+
f
26
+
27
+
Level of D? 3
28
+
Parent of C? A
29
+
Height of B? 2
30
+
Depth of F? 3
31
+
32
+
### Tree Traversal
33
+
34
+
DFS - depth first search, can be
35
+
- preorder: root, L, R
36
+
- inorder: L, root, R
37
+
- postorder: L, R, root (commonly used for deleting)
38
+
39
+
BFS - breadth first search, popularly
40
+
- search by level, left to right each level
41
+
42
+
### Quiz
43
+
44
+
a
45
+
/ \
46
+
b c
47
+
/ \
48
+
d e
49
+
\
50
+
f
51
+
52
+
Write out the post order traversal.
53
+
D, F, E, B, C, A
54
+
55
+
### Binary Trees
56
+
57
+
Each node can have at most 2 children.
58
+
59
+
**Searching:**
60
+
Any of the DFS or BFS traversals work here. O(n), having to look through til found.
61
+
62
+
**Deleting:**
63
+
Often starts off with a search to find the thing to delete.
64
+
When deleting, have to consider the children if you delete an internal node (parent).
65
+
If it's got one kid, you can just promote the kid up.
66
+
If it's got two, you will have to decide how to shift around the elements. You can search til you hit a leaf and promote the leaf up if you don't care about order.
67
+
68
+
**Inserting:**
69
+
If there's no order, just stick it in as a child somewhere. Move down tree from root looking for an open spot.
70
+
Worse case is O(height). What's the height of the binary tree?
71
+
72
+
A perfect tree has all children for every parent til the even leaf nodes at the end. Perfect trees have nodes equal to 2^(level-1).
0 commit comments