Professional Documents
Culture Documents
CS623: Data Structures & Algorithm Analysis: Chapter 3: Tree
CS623: Data Structures & Algorithm Analysis: Chapter 3: Tree
Analysis
Chapter 3: Tree
Compiled By Atnafu J. 1
Tree: Recursive Definition
A general tree is a finite set of nodes, i.e. either empty or
not, which has a designated node called the root node from
which (hierarchically) descend zero or more sub-trees. A
number of sub-trees may be constituted from the same tree
by rooting at each of the nodes in a recursive manner.
Compiled By Atnafu J. 2
Tree: Non recursive Definition
B E F
C D G H I
Compiled By Atnafu J. 3
Tree: a Rooted Tree
A rooted tree is a tree with the
following properties.
• One node is distinguished as Root node
the root. A
• Every node c, except the root, is
connected by an edge from B E F
exactly one other node p. Node
p is c's parent, and c is one of
p's children. C D G H I
• A unique path traverses from
the root to each node. The
J K
number of edges that must be L
followed is the path length.
Compiled By Atnafu J. M N 4
Terminologies
• A node that has a sub-tree is the parent of that sub-tree
(e.g. node A has three sub-trees and is the parent of
nodes B, C and D).
• A node which is not a parent is called a leaf (C, D, E, G, H,
I)
• An internal node is any node that has at least one non-
empty child.
• Every node in a tree is the root of some sub-tree (even if
an empty one).
• The number of sub-trees rooted at a node is called the
degree of that node. (E.g. node F is of degree 3)
• The degree of the tree is the degree of the node that has
the maximum degree.
Compiled By Atnafu J. 5
Terminologies
B C
D E F
F G H I
Compiled By Atnafu J. 7
Something to Ponder
91 83
77 64 63
14 48 55 7
Compiled By Atnafu J. 10
Example: Array Implementation
99
0
91 83
1 2
77 64 D 63
3 4 5 6
14 48 D 55 D D 7 D
7 8 9 10 11 12 13 14
Compiled By Atnafu J. 11
Example: Array Implementation
0 99 Depth = 3
1 91 Array Size = 23+1- 1= 15
2 83
3 77 99
4 64 0
91
5 Dummy 83
6 63 1 2
7 14
8 48 77 64 D 63
9 Dummy 3 4 5 6
10 55
11 Dummy 14 48 D 55 D D 7 D
12 Dummy 7 8 9 10 11 12 13 14
13 7
14 Dummy
Compiled By Atnafu J. 12
Array Implementation...
• Given a child, its parent node can be identified
(easily) and vice versa
• Parent(i) = (i-1)/2
• Left(i) = 2i + 1
• Right(i) = 2i + 2
Compiled By Atnafu J. 13
Exercise: Array Implementation of BT
Compiled By Atnafu J. 14
Array Implementation of BT
Efficiency Consideration
Adv:
- Simplicity
- Given a child, its parent node can be identified (easily) and
vice versa
Disadv:
- Wastage of space (esp. if the tree is not balanced)
- Reordering the elements due to shifting in case of deletion.
Compiled By Atnafu J. 15
Pointer Implementation of BT
Node Construction/Declaration:
template <class T>
struct node {
T data;
node<T> * left;
node<T> * right;
};
BT Construction:
node<int> * root; // contains the address of the root node
Compiled By Atnafu J. 16
BT Operations
Compiled By Atnafu J. 17
Create()
Compiled By Atnafu J. 18
isEmpty()
Compiled By Atnafu J. 19
Tree Traversal
Compiled By Atnafu J. 20
Breadth First Traversal
29
26 31
45, 36, 76 , 23, 39, 56, 89, 29, 41, 48, 69, 115, 26, 31
Compiled By Atnafu J. 22
Breadth First: Top-down, left to right
template <class T>
void bredthFirst(tNode<T> * root) {
queue<tNode<T> *> q;
tNode<T> * p=root;
if (p !=NULL) {
enqueue(q, p);
while(!isEmpty(q)){
p=dequeue(q);
“visit” p->data;
if(p->left != NULL)
enqueue(q, p->left);
if(p->right != NULL)
enqueue(q, p->right);
}
}
Compiled By Atnafu J. 23
}
Breadth First Bottom-up, left to right:
Exercise
Compiled By Atnafu J. 24
Depth First Traversal
This traversal proceeds as far as possible to the left(or right), then back
up until the first crossroad , goes one step to the right(or left), and again
as far as possible to the left(or right). This process will be repeated until
all nodes are visited.
Visit the children before the sibling.
There are six variation based on when the node is visited:
• Pre-order, left to right (VLR) • Pre-order, right to left (VRL)
• In-order, left to right (LVR) • In-order, right to left (RVL)
• Post-order, left to right (LRV) • Post-order, right to left (RLV)
If the move is always from left to right, we will have only three
traversal(the first column): pre-order, In-order and Post-order.
Implementation of this kind of traversal is straightforward if we use
recursion. Alternatively it can be implemented using stack iteratively.
Compiled By Atnafu J. 25
Pre-Order Traversal
Compiled By Atnafu J. 26
Pre-Order Traversal
29
26 31
45, 36, 23, 29, 26, 31, 39, 41, 76, 56, 48, 69, 89, 115
Compiled By Atnafu J. 27
Exercise: Pre-order Traversal
50
70
20
30
10
40
25
12
4
15
8
0 18
13
16
Compiled By Atnafu J. 28
Pre-Order Traversal Recursive
Compiled By Atnafu J. 30
Pre-Order Traversal Iterative
• Node Declaration for the tree
template <class T>
struct tnode{
T data;
tnode* left;
tnode* right;
};
• Node Declaration for the stack
template <class T>
struct snode {
tnode<T> * data;
snode *next;
};
Compiled By Atnafu J. 31
Pre-Order Traversal Iterative
template <class T>
void Preorder(tnode<T> *root ) {
/* prints tree in preorder iteratively using a stack. */
snode< tnode<T> *>* top=NULL;
if(root != NULL){
push( top, root);
while( top!= NULL ) {
pop(top, root);
cout << root->data << ‘\t’; // “visit” root->data;
if( root->right != NULL )
push( top, root->right );
if( root->left != NULL )
root=root->left;
}
}
}
Compiled By Atnafu J. 32
Post-Order Traversal
Compiled By Atnafu J. 33
Post-Order Traversal
50
70
20
30
10
40
25
12
4
15
8
0 18
13
16
Compiled By Atnafu J. 35
Post-Order Traversal
Compiled By Atnafu J. 37
Post-Order Iterative Traversal
Using One stack: Exercise
The idea is to move down to leftmost node using left pointer. While
moving down, push root’s right child and root to stack. Once we reach
leftmost node, print it if it doesn’t have a right child. If it has a right child,
then change root so that the right child is processed before. This will be
repeated until the stack is empty.
1.1 Create an empty stack
2.1 Do following while root is not NULL
a) Push root's right child and then root to stack
b) Set root as root's left child.
2.2 Pop an item from stack and set it as root.
a) If the popped item has a right child and the right child is at top of stack,
then remove the right child from stack, push the root back and set root
as root's right child.
b) Else print root's data and set root as NULL.
2.3 Repeat steps 2.1 and 2.2Compiled
whileBystack
Atnafu J.
is not empty. 38
In-Order Traversal
Compiled By Atnafu J. 39
In-Order Traversal
23, 36, 39, 41, 45, 48, 56, 69, 76, 89, 115
Compiled By Atnafu J. 40
Exercise: In-order Traversal
50
70
20
30
10
40
25
12
4
15
8
0 18
13
16
Compiled By Atnafu J. 41
In-Order Traversal
Compiled By Atnafu J. 43
Find an item: returns a pointer to the node
containing item; Null, otherwise. [Recursive
Solution]
template <class T>
node<T>* find(node<T>* root, T key) {
node<T>* pos;
if (root ==NULL)
pos=NULL;
else if (root->data == key)
pos=root;
else{
pos=find (root->left, key);
if(pos == NULL)
pos=find (root->right, key) ;
}
return pos;
} Compiled By Atnafu J. 44
Ordered Binary Tree
Compiled By Atnafu J. 45
Binary Search Tree
A binary search tree (BST) is a binary tree with one extra property:
• the key value of each node is greater than the key values of
all nodes in each left sub tree and smaller than the value of
all nodes in each right sub tree.
Compiled By Atnafu J. 47
Operation on BST
• Create(root)
• isEmpty(root)
• Traverse(root): Visit every node in the order relative to the
hierarchy of the nodes in the tree.
• Find(root, item): return the location of the data item in
the tree if it is found; an appropriate flag otherwise.
• Add(root, node): Adds to the tree a new node while
maintaining the appropriate hierarchical relationships
within the root.
• Remove(root, node): Delete a node while maintaining the
appropriate hierarchical relationship within the tree.
Compiled By Atnafu J. 48
Create()
Compiled By Atnafu J. 49
IsEmpty()
Compiled By Atnafu J. 50
In-Order Traversal
Compiled By Atnafu J. 51
Find an item: returns a pointer to the
node containing item; Null, otherwise.
[Recursive Solution]
template <class T>
node<T> * find(node<T> * root, T item) {
if (root ==NULL)
return NULL; Performance Analysis:
else if (item == root->data) Best Case?
return root; Worst Case?
else if (item < root->data)
return find(root->left, item);
else
return find(root->right, item);
}
Compiled By Atnafu J. 52
Find an item: returns a pointer to the
node containing item; Null, otherwise.
[Iterative Solution]
template <class T>
node<T> * find(node<T> * root, T item) {
while (root != NULL)
{
Performance Analysis:
if (item == root->data)
return root; Best Case?
else if (item < root->data) Worst Case?
root = root->left;
else
root = root -> right;
}
return NULL;
}
Compiled By Atnafu J. 53
Add an item in the BST
root
Compiled By Atnafu J. 55
BST Add Example
37
Compiled By Atnafu J. 56
BST Add Example
37
27
Compiled By Atnafu J. 57
Add an item into a BST - Recursive
template <class T>
void add(node<T> * & root, T item) {
node<T> * p;
if (root ==NULL){ Performance Analysis:
p=new node<T>; Best Case?
p->left=p->right=NULL; Worst Case?
p->data=item;
root = p;
} else if (item < root->data)
add(root->left, item);
else if (item > root->data)
add(root->right, item);
}
Q: Is duplicate data handled?
Compiled By Atnafu J. 58
Add an item into a BST - Iterative
template <class T>
void addIterative(node<T>* & root, T item) {
p=new (nothrow) node<T>;
p->left=p->right=NULL;
p->data=item;
Performance Analysis:
if (root ==NULL){ Best Case?
root = p; Worst Case?
} else { node<T> * newRoot = root;
int added = 0;
while (!added) {
if (item < newRoot->data) {
if (newRoot->left == NULL)
{newRoot->left = p; added = 1;}
else newRoot = newRoot->left;
} else if (item > newRoot->data) {
if (newRoot->right == NULL)
{newRoot->right = p; added = 1;}
else newRoot = newRoot->right;
}
} Compiled By Atnafu J. 59
}
Exercise
Compiled By Atnafu J. 61
Add an item into a BST Adding Add
duplicates to the left
template <class T>
void add(node<T>* & root, T item) {
node<T> * p;
if (root ==NULL){
p=new (nothrow) node<T>;
p->left=p->right=NULL;
p->data=item;
root = p;
}else if (item <= root->data)
add(root->left, item);
else
add(root->right, item);
} Compiled By Atnafu J. 62
Add an item into a BST
Add duplicates to the right
template <class T>
void add(node<T>* & root, T item) {
node<T> * p;
if (root ==NULL){
p=new (nothrow) node<T>;
p->left=p->right=NULL;
p->data=item;
root = p;
} else if (item >= root->data)
add(root->right, item);
else
add(root->left, item);
} Compiled By Atnafu J. 63
Add an item into a BST
Add “dup” in the node
Node Construction/Declaration:
template <class T>
struct node {
T data;
int dup;
node * left;
node * right;
};
BST Construction:
node<T> * root; Compiled By Atnafu J. 64
Add an item into a BST
with “dup”
template <class T>
void add(node<T>* & root, T item) {
node<T> * p;
if (root ==NULL){
p=new (nothrow) node<T>;
p->left=p->right=NULL;
p->data=item;p->dup=1;
root = p;
} else if (item == root->data)
root->dup++;
else if (item < root->data)
add(root->left, item);
else
add(root->right, item);
Compiled By Atnafu J. 65
}
In-Order Traversal of a BST
with “dup”
Compiled By Atnafu J. 67
Delete an item from BST
Compiled By Atnafu J. 68
Delete: Different Scenarios
Analysis:
Case 1: When the item to be deleted is a leaf
Case 2: Deleted element have only one sub
tree(right or left sub tree)
Case 3: Deleted element has two sub tree
Compiled By Atnafu J. 69
Case 1: Deletion of a Leaf Node
Node to be deleted N
Compiled By Atnafu J. 70
Case 2: Deletion of an Internal Node
Having Only One Sub Tree
• Given a node N to be deleted which has only right or left sub
tree
• Divert its parent pointer to its right or left sibling
• Delete N
P
P
N
N
Node to be deleted
Compiled By Atnafu J. 71
Case 2: Deletion of an Internal Node
Having Only One Sub Tree
P
P
N
N
Node to be deleted
Compiled By Atnafu J. 72
Case 3: Deleted element has Left &
Right Sub Tree
• Given a node N to be deleted which has left and right sub tree
• Find the node with the maximum value from its left sub tree (in order
predecessor of N) or the minimum value from its right sub tree (in order
successor of N)
• This gives you a node with a maximum of one sub tree
• Swap the data of the two nodes
• Delete the node with the search key (has zero or one sub tree)
P
Node to be deleted
N
73
Compiled By Atnafu J.
Case 3:Max from Left & Min from
Right
P
P
N
N
Compiled By Atnafu J. 74
Case 3: Swap
P
P
N Swap them N Swap them
Compiled By Atnafu J. 75
Case 3: After Delete
Compiled By Atnafu J. 76
Case 3: Node to be Deleted
P
P
N
N
Node To be deleted
Node To be Deleted
Compiled By Atnafu J. 77
Exercise: Delete
50
70
20
30
Delete 13, 12, 18, 20
10
40
25
12
4
15
8
0 18
13
16
Compiled By Atnafu J. 78
Delete an item from a BST : Implementation
template <class T>
void remove(node<T>* & root, T item) { Root
if(root != NULL){ 50
if(item < root->data) 70
remove(root->left , item); 20
else if(item > root->data)
remove(root->right , item); 30
else{
node<T> * temp=root; 10
25 40
T data; 11
if(root->left == NULL){ 4
root=root->right; 16
delete temp; 8
}else if(root->right == NULL){ 0 19
root=root->left; 14
delete temp;
17
}else{ 13
getPredecessor (root->left, data);
root->data=data; 12
remove(root->left, data); }
} Compiled By Atnafu J. 79
}
Delete: getPredecessor…
Root
50
17
13
12
Compiled By Atnafu J. 80
Delete an item from a BST : Option2
template <class T> Root
void remove(node<T>* & root, T item) { 50
if (root !=NULL)
70
if (item < root->data)
20
remove(root->left , item);
else if (item > root->data) 30
remove(root->right, item);
10
else { 25
40
node<T> * q = root; 11
if (root->right == NULL) 4
root=root->left; 16
8
else if (root->left == NULL) 0 19
root=root->right; 14
else
17
del(q->left, q); // see next slide for del() 13
delete q;
} 12
Compiled By Atnafu J. 81
}
Delete an item from a BST : Option2
template <class T> Root
void del(node<T> * & root, node<T> * & q) { 50
if (root->right != NULL) 70
del(root->right, q); 20
else {
q->data = root->data; 30
q =root; 10
40
root = root->left; 25
} 11
} 4
16
8
0 19
14
17
13
Compiled By Atnafu J. 82
12
Something to Ponder
Compiled By Atnafu J. 83
Delete an item from a BST
with “dup”
Left as an exercise!
Compiled By Atnafu J. 84
Analysis Binary Search Tree
Compiled By Atnafu J. 85
Expression Tree
An expression tree is a tree that represents an infix expression. At its
leaves the tree contains operands (e.g., constants or variable names) and
the internal nodes contain operators.
Nodes can have more than two children. A node also may have only one
child, as is the case with the unary minus operator.
-
+ D
Binary Expression Tree
(A + B*C) - D
A *
B C
Traverse the binary expression using preorder, inorder and postorder traversal.
And give your observation.
Compiled By Atnafu J. 86
Infix Algebraic Expression
Exercise: (a + b/c)+ d * (e – f + g)
Compiled By Atnafu J. 87
Expression Tree Exercise
Compiled By Atnafu J. 88
Expression Tree Exercise
Compiled By Atnafu J. 89