12-DSA-Tree Traversal
12-DSA-Tree Traversal
Binary Trees
Implementation
Tree ADT
• Data Type: Any type of objects can be stored in a tree
• Accessor methods
• root() – return the root of the tree
• parent(p) – return the parent of a node
• children(p) – return the children of a node
• Query methods
• size() – return the number of nodes in the tree
• isEmpty() – return true if the tree is empty
• elements() – return all elements
• isRoot(p) – return true if node p is the root
• Other methods
• Tree traversal, Node addition/deletion, create/destroy
Binary Tree Storage
• Contiguous storage
• Linked list-based storage
Array Storage
• We can store a binary tree as an array
4 D
D E F G
5 E
6 F
H I 7 G
8 H
Array Storage
• The children of the node with index k are in 2k and 2k+1
• The parent of node with index k is in k÷2
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Array Storage Example
• Node 10 has index 5
• Its children 13 and 23 have indices 10 and 11, respectively
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Array Storage Example
• Node 10 has index 5
• Its children 13 and 23 have indices 10 and 11, respectively
• Its parent is node 9 with index 5/2 = 2
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Array Storage: Disadvantage
• Why not store any tree as an array using breadth-first
traversals?
• There is a significant potential for a lot of wasted memory
B C
D E F
G H I J K