Data Structures & Algorithm Design: Trees
Data Structures & Algorithm Design: Trees
Algorithm Design
Trees
2020
10-1
Tree Definition
• Tree: a set of elements of the same type
such that
• it has a distinguished element called the root
from which descend zero or more trees
(subtrees)
10-2
Tree Terminology
• Nodes: the elements in the tree
• Edges: connections between nodes
• Root: the distinguished element that is the
origin of the tree
• There is only one root node in a tree
• Leaf node: a node without an edge to another
node
• Interior node: a node that is not a leaf node
• Empty tree has no nodes and no edges
10-3
Tree Terminology
• Parent or predecessor: the node directly
above in the hierarchy
• A node can have only one parent
10-4
Tree Terminology
10-5
Tree Terminology
Root
Subtrees of
the root
10-6
Subtrees
Subtrees of the
node labeled E
10-7
Tree Terminology
Root
Interior
nodes
Leaf
nodes
10-8
Height of a Tree
10-9
Level and Degree of a Node
10-10
Level of a Node
Level 0
Level 1
Level 2
Level 3
10-11
Binary Trees
10-12
Binary Trees
10-13
Binary Trees
10-14
Binary Trees
A
B C
D E F G
H I J K
10-15
Binary Tree Properties
The number of nodes n in a complete
binary tree is at least n = 2h and at most
n = 2(h + 1) − 1 where h is the height of the
tree.
The number of leaf nodes L in a complete
binary tree can be found using this
formula: L = 2h where h is the height of the
tree.
The number of nodes n in a perfect binary
tree can also be found using this formula:
n = 2L − 1 where L is the number of leaf
nodes in the tree.
16
Binary Search Tree
10-17
Binary Search Tree Construction
10-18
Declaration BT
A node consists of three fields such as :
• Left Child (LChild)
• Information of the Node (Info)
• Right Child (RChild)
struct node {
int info;
struct node *left;
struct node *right;
};
19
Binary Search Tree – Insertion
10-20
Insertion- Examples
5
10 10
2 45
5 30 5 45
30
2 25 45 2 25 30
10
25
20
10-22
Binary Search Tree
Given the following sequence of numbers,
10-26
Traversing :
Means visiting all the nodes of the tree, in
some specific order for processing.
There are THREE ways of Traversing a
Tree
1. Preoder Traversal
2. Inorder Traversal
3. Postorder Traversal
4. Levelorder Traversal
Preorder Traversal Method
10-30
Inorder Traversal Method
10-32
Postorder Traversal Method
}}
10-36
Levelorder Traversal Method