Trees
Froilan De Guzman
Learning outcomes:
- To discuss the basic concepts of tree data structure.
- To discuss the essential components of a tree.
2
What is tree?
A tree is a nonlinear hierarchical data structure that consists of nodes
connected by edges.
https://www.programiz.com/dsa/trees
Different tree data structures allow quicker and easier access to the data as it
is a non-linear data structure.
3
Tree terminologies
Node - A node is an entity that
contains a key or value and pointers
to its child nodes. The last nodes of
each path are called leaf nodes or
external nodes that do not contain a
link/pointer to child nodes. The node
having at least a child node is called
an internal node.
Edge - It is the link between any two
nodes.
N = nodes
N – 1 = edges
4
Tree terminologies
Root - It is the topmost node of a
tree.
Height of a Node - The height of a
node is the number of edges from the
node to the deepest leaf (ie. the
longest path from the node to a leaf
node).
Depth of a Node - The depth of a
node is the number of edges from the
root to the node.
Height of a Tree - The height of a
Tree is the height of the root node or
the depth of the deepest node.
5
Example of a tree
Source: https://www.tutorialspoint.com/data_structures_algorithms/tree_data_structure.htm 6
Given: A
Solve for the following:
1. Parent node of: B C
1. Node F
2. Node P
3. Node L
D
2. Child node of: E F G H
1. Node E
2. Node I
3. Node M I J K L M
3. Siblings of:
1. Node R
2. Node E
N O P Q
3. Node I R
S 7
Given: A
Solve for the following:
1. Parent node of: B C
1. Node F = B
2. Node P = K
3. Node L = H
D
2. Child node of: E F G H
1. Node E = J, K
2. Node I = N
3. Node M = none I J K L M
3. Siblings of:
1. Node R = Q
2. Node E = D, F
N O P Q
3. Node I = none R
S 8
Given: A
Solve for the following:
1. Height of B C
1. Node D
2. Node B
3. Node O
4. Node P D E F G H
2. Depth of:
1. Node C
2. Node N I J K L M
3. Node Q
3. Height of the tree
N O P Q R
S 9
Given: A
Solve for the following:
1. Height of B C
1. Node D = 2
2. Node B = 4
3. Node O = 1
4. Node P = 0 D E F G H
2. Depth of:
1. Node C = 1
2. Node N = 4 I J K L M
3. Node Q = 4
3. Height of the tree = 5
N O P Q R
S 10
Given: A
Solve for the following:
1. Path between B C
1. K and G
2. D and L
3. I and P
4. Q and E D E F G H
5. O and M
I J K L M
N O P Q R
S 11
Given: A
Solve for the following:
1. Path between B C
1. K and G = 5
2. D and L = 5
3. I and P = 5
4. Q and E = 6 D E F G H
5. O and M = 7
I J K L M
N O P Q R
S 12
References:
- https://www.programiz.com/dsa/trees
- https://www.tutorialspoint.com/data_structures_algorithms/tree_data_structure.htm
13