Depth of a tree: The maximum level of any leaf in the tree Degree of a node : The number of subtrees of a node Terminal node or leaf : A node of degree zero Parent and Siblings : Each ro
Trang 1DATA STRUCTURE AND ALGORITHMS – DSA315
Spring 2010
Lecture #09_10 Nguyen Tuan Anh tuananh@hanu.vn
Trang 2• What it is (conceptual)
• Why we use it (applications)
• How we implement it (implementation)
Trang 3Definition and Terminology
Other Representations of Trees
Binary Tree
Internal Path Length
Trang 4How We View a Tree
Nature Lovers View Computer Scientists View
Trang 5Definition and Terminology
Definition:
Tree is defined as a finite set T of one
or more nodes such that
a) there is one specially designated node called
the root of the tree, root(T) and
b) the remaining nodes (excluding the root) are
partitioned into m ≥ 0 disjoint sets T1 , T2 ,
, Tm and
each of these sets in turn is a tree The trees
T1 , T2 , , Tm are called the subtrees of
Trang 6Definition and Terminology
Terminology:
Level of node : The level of a node with respect to T is defined
recursively: The level of root(T) is zero, and the level of any other node is one higher than that node's level with respect to the subtree of root(T) containing it.
Depth of a tree: The maximum level of any leaf in the tree
Degree of a node : The number of subtrees of a node
Terminal node or leaf : A node of degree zero
Parent and Siblings : Each root is said to be the parent of the roots of its
subtrees, and the latter are said to be siblings; they are children of their parent.
Ancestor and Descendant : Ancestor and descendant can also be used to
denote the relationship that may span several level
of tree.
Trang 7Definition and Terminology
Level of node : State the levels of all the nodes:
A: , B: , C: , D: , E: , F: , G: , H: , I:
Root of a tree: Root of the tree is: _
Depth of a tree: Depth of the tree is: _
Degree of a node : State the degrees of:
A: , B: , C: , D: , E: , F: , G: , H: , I:
Terminal node or leaf: State all the leaf nodes: _ Branch node: State all the branch nodes: _
Trang 8Definition and Terminology
Parent and Siblings:
State the parents of:A: _, B: _, C: _,
D: _, E: _, F: _, G: _, H: _, I: _
State the siblings of: A: _, B: _,
C: _, D: _, E: _, F: _, G: _, H: _, I: _ Ancestor and Descendant:
State the ancesters of: A: , B: , C: , D: _,
E: _, F: _, G: _, H: _, I: _
State the descendants of: A: _,
B: _, C: _, D: , E: , F: , G: , H: , I:
Trang 9Binary Trees
• A binary tree is a tree with the
following properties:
– Each internal node has at most two
children (exactly two for proper
binary trees)
– The children of a node are an
ordered pair
• We call the children of an internal
node left child and right child
• Alternative recursive definition: a
binary tree is either
– a tree consisting of a single node,
or
– a tree whose root has an ordered
pair of children, each of which is a
binary tree
• Applications:
– arithmetic expressions– decision processes– searching
Trang 10Arithmetic Expression Tree
• Binary tree associated with an arithmetic expression
– internal nodes: operators
– external nodes: operands
• Example: arithmetic expression tree for the expression
Trang 11Decision Tree
• Binary tree associated with a decision process
– internal nodes: questions with yes/no answer
– external nodes: decisions
• Example: dining decision
Want a fast meal?
Trang 12Binary Tree
Definition:
Binary tree can be defined as a finite
set of nodes that either
–is empty, or
–consists of
(1) a root, and
(2) the elements of 2
disjoint binary trees
called the left and right subtrees of the root.
Examples of Binary tree:
Trang 135 4
• Each node has 0, 1, or 2 subtrees.
• Each node has 0, 1, 2, or many
• We don’t distinguish subtrees
according to their orders
For example, these are _:
1
2 3
4 5
1 2 3
5 4
6
7
6 7
• A tree must have at least 1 node • A binary tree may be empty
Trang 14Full Binary Tree: No of nodes = 2depth_of_tree +1-1
Example:
Properties of Binary Tree
Maximum number of nodes Consider the levels of a binary tree: level 0, level 1, level 2, Maximum number of nodes on a level is 2level_id.
Maximum number of nodes in a binary tree is 2depth_of_tree+1 - 1.
Trang 15Properties of Binary Tree
Complete Binary Tree:
…
• The bottom level:
• Each leaf in a tree is either at level k or level k-1
• Each node has exactly 2 subtrees at level 0 to level
k-2
• For any node nd with a right descendant at level k,
all the left descendants of nd that are leaves are
also at level k or below.
A complete binary tree is like a full binary tree,But in a complete binary tree,
Definition: A binary tree with n nodes and depth k is complete iff its
nodes correspond to the nodes numbered from 1 to n in the fully binary tree of depth k.
The filled slots are at the left
of the empty slots (if any).
• Except the bottom level: all are fully filled.
1
8 9 10 11 12
Trang 16Array Representation of Binary Tree
We can represent binary
trees using array by
applying this number
C D
E
0 1 3
7 15
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15Array Representation
of Binary Tree
Trang 17Array Representation of Binary Tree
Left(i) = 2i+1 Right(i) = 2i+2
Parent of a node at slot i:
x: “Floor” The greatest integer
less than x
x: “Ceiling” The least integer greater
than x
For any slot i,
If i is odd: it represents a left son.
If i is even (but not zero): it represents a right son.
The node at the right of the represented node of i (if any), is at i+1 The node at the left of the represented node of i (if any), is at i-1.
Trang 18Array Representation of Binary Tree
A B
C D
E
0 1 3
7 15
A B - C - - - D -
-0 1 2 3 4 5 6 7 8 9 1-0 11 12 13 14 15
- - - E
must be flagged for non-full binary tree.
Solutions :1 put a special value in the location
2 Add a “used” field (true/false) to each node.
Advantages and Disadvantages of using array to represent binary tree:
_ Simpler
_ Save storage for trees known to be almost full
_ Waste of space (except complete binary tree)
_ Maximum size of the tree is fixed in advance
_ Inadequacy: insertion and deletion of nodes from the middle of a tree require
the movement of potentially many nodes
Trang 19Array Representation of Binary Tree
Method 1 : Compare each number with those precede (or after) it.
Eg To find all duplicates in <7 4 5 9 5 8 3 3>, we need to
7 4 5 9 5 8 3 3
7 4 5 9 5 8 3 3
7 4 5 9 5 8 3 3
7 4 5 9 5 8 3 3
Method 2 - Use a special binary tree (Binary Search Tree), T :
• Read number by number.
• Each time compare the number with the contents of T
• If it is found duplicated, then output, otherwise add it to T
Application: Find all duplicates in a list of numbers.
Trang 20Array Representation of Binary Tree
Using Binary Search Tree to Find All Duplicates in a List of Numbers
Example: To find all duplicates in < 7 4 5 9 5 8 3 3>:
7 7 4 7 4 5 7 4 5 9 7 4 5 9 5 7 4 5 9 5 87 4 5 9 5 8 37 4 5 9 5 8 3 3
7 7
4
7 4 5
7 4 5
9
7 4 5
9 8
7 4 5
9 8 3
7 4 5
9 8 3
x
Method 2 - Use a special binary tree (Binary Search Tree), T:
• Read number by number.
• Each time compare the number with the contents of T.
• If it is found duplicated, then output, otherwise add it to T.
We’ll discuss
Binary Sear ch Tree
in a later topic.
Briefly, in a Binary Search Tree ,
Each node of the tree contains a number
The number of each node is
• bigger than the numbers in the left subtree.
• smaller than the numbers in the right subtree.
7 4 5
9
Trang 217 7 4 7 4 5 7 4 5 9 7 4 5 9 5 7 4 5 9 5 8 7 4 5 9 5 8 3 7 4 5 9 5 8 3 3
4
7 4 5
7 4 5
9
7 4 5
9 8
7 4 5
9 8 3
7 4 5
9 8 3
7 4 5
9
The steps to insert a ‘5’:
1 Compare the root with ‘5’ It is bigger than ‘5’, so,
2 Go to left subtree, which has root = ‘4’, that is smaller than
Array Representation of Binary Tree
Using Binary Search Tree to Find All Duplicates in a List of Numbers
7 4
Example 1.
The steps to insert a ‘5’:
1 <same as example 1.>
2 <same as example 1.>
3 Go to the right subtree of ‘4’, which has the root =
‘5’ Found=>no need to insert
7 4 5
9 8 3
Example 2.
Trang 22Method 2 - Use a special binary search tree (Binary Search Tree), T:
• Read number by number.
• Each time compare the number with the contents of T.
• If it is found duplicated, then output, otherwise add it to T.
Array Representation of Binary Tree
Using Binary Search Tree to Find All Duplicates in a List of Numbers
Exercise:
Create a binary search tree according to the input sequence:
<3, 5, 0, 2, 7, 9, 6, 8>
Trang 23Method 2 - Use a special binary search tree (Binary Search Tree), T:
• Read number by number.
• Each time compare the number with the contents of T.
• If it is found duplicated, then output, otherwise add it to T.
Array Representation of Binary Tree
Using Binary Search Tree to Find All Duplicates in a List of Numbers
The algorithm:
Initialize an empty binary tree
For each input number:
Traverse the tree from top to bottom
For each node reached in traversal:
case1: If the node is empty,
ie The input number is not found in the tree ==> add it.case 2: If the node content is same as the number,
output the input number as a duplicate
case 3: If the node content is larger (smaller) than input number,
then prepare for traversal of its left (right) subtree
The traversal ends due to case 1 or 2, or due to going beyond the array
If it is due to going beyond the array, then output error message and exit
7 4 5
9 8 3
5
Trang 24void InitializeTree() { } //Set the used field of each slot as false.
void AddNode(int NodeID, int value) { } //Set a given node with a specified value
void main()
{ … // Initialize the tree
… // For each number in a sequence, determine whether it is
// the same as a previous one.}
Array Representation of Binary Tree
Using Binary Search Tree to Find All Duplicates in a List of Numbers
Trang 25//InitializeTree: Set the used field of each slot as false.
void InitializeTree(){ int i;
for (i = 0; i<TOTAL_SLOTS; i++)
node[i].used = FALSE;
}
//AddNode: Add a node at a given position
void AddNode(int NodeID, int value) { if (NodeID >= TOTAL_SLOTS)
Binary Search Tree to
Find All Duplicates in a
List of Numbers
Trang 26…void main(){ int seq[12]={3,5,0,2,7,9,5,6,3,7,0,8};
int NodeID, i;
InitializeTree(); //Initialize the tree
for(i=0;i<12;i++){ NodeID=0;
while ((NodeID < TOTAL_SLOTS))
{ if (!node[NodeID].used) { AddNode(NodeID,seq[i]);
break;
}
if (seq[i] == node[NodeID].info) { printf("%d is a duplicate\n", seq[i]);
exit(1);
}}}
For each input number:
Traverse the tree from top to bottom
For each node reached in traversal:
case1: If the node is empty, ie The input no
is not found in the tree => add it.
case 2: If the node content is same as the
number, output the input number as
a duplicate
case 3: If the node content is larger (smaller)
than input no., then prepare for
traversal of its left (right) subtree.
The traversal ends due to case 1 or
2, or due to going beyond the array
If it is due to going beyond the array,
then output error message and exit.
Array Representation of Binary
Tree
Using Binary Search Tree to Find All
Duplicates in a List of Numbers
Trang 27Exercise:
Create a program that Generates 100000 random numbers within the range: 0-999.
Add 2 functions into this programs:
The first one counts all duplicates by using a binary search tree implemented as an array (note: set the array size to 5,000,000
or larger).
The second one counts all duplicates by a sequential searching method (Compare each number with those after it.)
Test the speeds of these two functions: which one is faster?
Array Representation of Binary Tree
Using Binary Search Tree to Find All Duplicates in a List of Numbers
Trang 28Link Representation of Binary Tree
Link Representation of Binary Tree
• Each node can contains info, left, right, father fields
• where left, right, father fields are node pointers
pointing to the node's left son, right son, and father,
respectively
right left
info father
right left
info typedef struct node *struct node NodePtr;
{ int info ;
NodePtr left ; NodePtr right ; };
• If the tree is always traversed in
downward fashion
(from root to leaves),
the father field is unnecessary.
left A right left B right left C right
left F right left G right left E right
T
• Let T be with type NodePtr If the tree
is empty, T = NULL; otherwise T is the address of the root node of the tree
• T->left and T->right point to the left and right subtrees of the root, respectively
Trang 29NodePtr maketree(int value) { } //create a new
void setleft(NodePtr p, int value) { } //create a new left child of a given node
void setright(NodePtr p, int value) { } //create a new right child of a given node
void main()
{ // For each number in a sequence, determine whether it is \
// the same as a previous one.}
Link Representation of Binary Tree
Using Binary Search Tree to Find All Duplicates in a List of Numbers
Trang 30… NodePtr maketree(int value) //create a new
Binary Search Tree to
Find All Duplicates in a
List of Numbers
Trang 31…void main(){ int i, seq[12]={ 3,5,0,2,7,9,5,6,3,7,0,8 };NodePtr p, T=maketree(seq[0]);
for(i=1;i<12;i++) {
p=T;
while (p->info!=seq[i]){ if (seq[i] < p->info)
else
}
}}
…void main(){ int i, seq[12]={ 3,5,0,2,7,9,5,6,3,7,0,8 };NodePtr p, T=maketree(seq[0]);
for(i=1;i<12;i++) {
p=T;
while (p->info!=seq[i]){ if (seq[i] < p->info)
if (p->left==NULL){ setleft(p,seq[i]);
break;
}else p=p->left;
else
if (p->right==NULL){ setright(p,seq[i]);
break;
}else p=p->right;
}
}}
…void main(){ int i, seq[12]={ 3,5,0,2,7,9,5,6,3,7,0,8 };NodePtr p, T=maketree(seq[0]);
for(i=1;i<12;i++) { BOOL bNewNodeCreated=FALSE;
p=T;
while (p->info!=seq[i]){ if (seq[i] < p->info)
if (p->left==NULL){ setleft(p,seq[i]);
bNewNodeCreated=TRUE;
break;
}else p=p->left;
else
if (p->right==NULL){ setright(p,seq[i]);
bNewNodeCreated=TRUE;
break;
}else p=p->right;
}
if (!bNewNodeCreated)printf("%d is a duplicate\n",seq[i]);
}}
The algorithm:
Create root node to store first no
Handle each remaining input no
Start at the root, traverse the tree
from top to bottom until we meet
the same value
store input no
and stop traversingelse go to left subtree
else (input no > current node)(we’ll look at the right sub-tree)
…
If no new node has been created for
the input number, it is a duplicate
Trang 32Binary Tree Operations - depth
Level of node : The level of root(T) is zero.
The level of any other node is one higher than that node's level with respect to the subtree of root(T) containing it.
Depth of a tree: The maximum level of any
leaf in the tree
Trang 33Binary Tree Operations - depth
//To determine the depth of a binary tree
int depth(NodePtr tree)
{ int DepthOfLeftSubTree, DepthOfRightSubTree;
if (tree == NULL)
return(0);
if ((tree->left == NULL) && (tree->right == NULL))
return(0); // the root is at level 0
Trang 34Binary Tree Operations - count_leaf
//To count the number of leaf nodes
int count_leaf(NodePtr tree)