Professional Documents
Culture Documents
2.1 Arrays Lists and Trees
2.1 Arrays Lists and Trees
and Trees
CS 251 – Data Structures
and Algorithms
Linear Data Structures Table of Contents
01 Arrays and Linked Lists
* Just a mention. We will talk more about graphs later in this course.
01
Linear Data Structures
Arrays and Linked Lists
Static Data Structure (i.e., fixed size)
Array array?
Keep track of next available cell?: Ο(1)
Sorry, to tracking: Ο(𝑛)
0 1 2 … n-2 n-1
Q: How much space is required to keep
A A0 A1 A2 … An-2 An-1 track of the next available cell?
One variable: Ο(1)
Time? 𝑇 𝑛 ≈ 𝑛 ∈ Ο(𝑛)
Space? 𝑇 𝑛 ≈ 𝑛 ∈ Ο(𝑛)
Usual strategy:
Full? Increase its size (double the current size)
Half empty? reduce its size (half the current size)
2D Array (Grid, Matrix)
A 0 1 2 … m-2 m-1
Linked List
// Pointer to the first node of the list
private Node<Item> first;
Linked List
insert an element at the start/end of a list?
Start? New node + update pointer: 𝑂(1)
End? Keep track of last node?: 𝑂(1)
End? Sorry, to tracking: 𝑂(𝑛)
* Just a mention. We will talk more about graphs later in this course.
Tree
A Dynamic Non-Linear Data Structure
2𝑖 = 2ℎ+1 − 1
M N O 𝑖=0
Full binary tree facts
B C Function preorder(node)
if (node != null)
visit(node)
preorder(leftChild(node))
D E G preorder(rightChild(node))
end if
End function
H I J K L preorder(A) = A, B, D, H, E, I, J, M, N, C, G, K, L O
M N O
Binary tree traversal: Inorder
A
Visit a node after its left descendants and
before its right descendants.
B C
Function inorder(node)
if (node != null)
inorder(leftChild(node))
D E G visit(node)
inorder(rightChild(node))
end if
End function
H I J K L
inorder(A) = H, D, B, I, E, M, J, N, A, C, K, G, O, L
M N O
Binary tree traversal: postorder
A
Visit a node after its descendants.
B C Function postorder(node)
if (node != null)
postorder(leftChild(node))
postorder(rightChild(node))
D E G visit(node)
end if
End function
H I J K L postorder(A) = H, D, I, M, N, J, E, B, K, O, L, G, C, A
M N O
Balancing matters