2. Introduction
⢠Linear data structures
â Forms a sequence. E.g., list, stack and queue
â Each element has a unique successor & a unique predecessor
â two basic ways of representing linear structures in memory
⢠relationship between the elements by means of pointers
(links)
⢠using sequential organization, that is, arrays
⢠Non-linear data structures
â Used to represent the data containing hierarchical or
network relationship between the elements. E.g., tree and graph
â Each element may have more than one predecessor as well as
successor
â capable of expressing more complex relationships than linear
data structures
4. Definition of General Tree
⢠A tree T is defined recursively as follows:
ďA set of zero items is a tree, called the empty tree
(or null tree).
ďThe collection can be empty or consists of a node
called root, R, and zero or more non-empty (sub)
trees T1, T2, âŚ, Tn.
5. Basic Terminology
Root: The root node is the topmost node in the tree
hierarchy. In other words, the root node is the one that
doesn't have any parent.
Root: the unique (beginning) vertex in a rooted tree.
e.g., b
6. Descendant: The immediate successor of the given
node is known as a descendant of a node.
e.g., m,n,h and i are descendants of e or b;
Child node: If the node is a descendant of any node,
then the node is known as a child node.
e.g., c,d,e and f are children of b;
j,k and l are children of f
Edge: refers to a directed/undirected edge from a
parent to its child
7. Parent â Any node except the root node has one edge
upward to a node called parent.
Parent: the root vertex is considered as parent of children
e.g., b is parent of c,d,e anf f; k is parent of o,p and q
Siblings: The nodes that have the same parent are known as
siblings.
e.g., c,d,e and f are siblings; j,k and l are siblings
8. Basic Terminology
Leaves(terminal or external nodes): The node of the
tree, which doesn't have any child node
e.g., c,g,m,n,j,âŚ.
Internal nodes/vertex:
A node has at least one child node or non-leaf node.
e.g., d,e,k,fâŚ
9. The degree of a node: is the number of subtrees it has.
The degree of a tree is the maximum degree of a node
in the tree. The degree of each leaf node is zero.
e.g., the above tree has degree 4; k has degree 3
Number of edges: If there are n nodes, then there
would n-1 edges.
10. Basic Terminology
Ancestor node:- An ancestor of a node is any predecessor
node on a path from the root to that node.
e.g., b,f and k are ancestors of o,p and q
Path: each node can be reached from the root through a unique
sequence of nodes called path.
The length of a path is the number of edges it contains
(which is one less than the number of nodes on the path).
11. The depth or level of a node: is the length of a node, which is
the length of a directed path from the root. e.g., depth of n is 3
ď The root node has 0 depth.
NB: The depth of a tree is equal to the depth of the deepest
leaf;
this is always equal to the height of the tree.
The height of a tree is given by the height of its root node.
12. Height of node x: The height of node x can be defined as the
longest path from the node x to the leaf node.
The height of a vertex/node: is the length of the longest path
from that node to a leaf that is a descendent of the node.
e.g., the height of d is 1;
height of b is 3;
all leaves are at height 0.
At each level of i, the maximum number of nodes is 2i.
13. Binary tree
⢠The Binary tree means that the node can have at most two
children. means each vertex in the tree has no children,
one child, or two children.
⢠If a vertex has two children, the first child is referred to as
the left child, and the second child is referred to as the right
child.
⢠If a vertex has only a single child, then that child may be
positioned as either a left child or a right child.
14. Types of Binary Tree
Full/ proper/ strict Binary tree
⢠A binary tree is a full binary if every nodes in a tree
either has two children or no child at all.
⢠The number of leaves in a full binary tree is always
one more than the number of internal vertices in the
tree.
15. ⢠A perfect (or balanced) binary tree: is a full
binary tree in which all leaves have the same depth.
⢠It is easy to show that the number of vertices in a
perfect binary tree is always 2h+1 -1 considering the
root at level 0 and a tree of height h.
16. ⢠Complete Binary Tree:- in which the length from the
root to any leaf node is either h or h-1. where h is
height of the tree.
⢠The complete binary tree is a tree in which all the
nodesare completely filled except the last level.
⢠In a complete binary tree, the nodes should be added
from the left.
17. Representation of a binary tree
⢠Each node in the binary tree contains one or more data
fields, and two pointers: one to the left child and the other
to the right child.
struct node {
Data field declarations;
node *left; // pointer to left child;
node *right; // pointer to right child;
};
node *RootPtr=NULL; /* root is external pointer that
holds the address of the root node permanently.*/
18. Representation of a binary tree
Left data right
Left data right Left data right
Left data right Left data right
Left data right
NULL NULL
NULL NULL NULL
NULL
NULL
RootPtr
19. Constructing an Expression tree
⢠An expression tree is a binary tree that stores values on leaf nodes
and operators on internal nodes.
Consider the expression in RPN: A B â C E F - * +
⢠Then we would perform the following.
1. Push A and B into stack ( a pointer to each of these nodes are put in the
stack)
2. Next, the binary operator (-) is read; pop A & B and build a tree; push the
tree (i.e. pointer to its root) into stack.
3. Push C, E, & F into stack (they are operands)
4. Next a (-) is read, so two pointers to E & F are popped, a new tree is
formed, & a pointer to it is pushed into stack.
5. Next, a (*) is read, so two pointers to C and subtree (on top) are popped
and a new tree is formed, & a pointer to it is pushed into stack.
6. Finally, the last symbol (+) is read, so two pointers to subtrees are popped,
a new tree is formed, and a pointer to this tree is left on stack.
21. Tree traversal
⢠Is the process of visiting each node in a tree exactly
once.
⢠We consider three methods for traversing a binary
tree.
â Preorder traversal
â Inorder traversal
â Postorder traversal
22. Tree traversal
⢠Preorder traversal: The nodes will be visited in the
following order.
â First process the root node.
â Then recursively visit all nodes in the left subtree;
â Finally, recursively visit all nodes in the right subtree.
Preorder traversal: 20, 12, 10, 16, 14, 26, 24, 22, 30, 28,
32
C++ implementation
void Preorder (Node *Rootnode) {
if(Rootnode ! = NULL){
cout<< Rootnode->Num;
Preorder(Rootnode->Left);
Preorder(Rootnode->Right);
} }
23. Tree traversal
⢠Inorder traversal: The nodes will be visited in the
following order.
â First recursively visit all nodes in the left subtree
â Then process the root node.
â Finally, recursively visit all nodes in the right subtree
Inorder traversal: 10, 12, 14, 16, 20, 22, 24, 26, 28, 30,
32
Used to display nodes in ascending order from a BST.
C++ implementation
void Inorder (Node *Rootnode) {
if(Rootnode ! = NULL){
Inorder(Rootnode->Left);
cout<< Rootnode->Num;
Inorder(Rootnode->Right);
} }
24. Tree traversal
⢠Postorder traversal: The nodes will be visited in the
following order.
â First recursively visit all nodes in the left subtree
â Then recursively visit all nodes in the right subtree
â Finally, process the root node
Postorder traversal: 10, 14, 16, 12, 22, 24, 28, 32, 30, 26, 20
C++ implementation
void Postorder (Node *Rootnode) {
if(Rootnode ! = NULL){
Postorder(Rootnode->Left);
Postorder(Rootnode->Right);
cout<< Rootnode->Num;
// or any operation on the node
}
}
25. Tree traversal
⢠A binary tree traversal can also be applied to generate
mathematical expression in infix, prefix, and postfix notation
from an expression tree.
â Preorder traversal: - used to generate prefix notation.
â Inorder traversal: - used to generate infix notation.
â Postorder traversal: - used to generate postfix notation.
Preorder traversal â prefix notation
+ â A * B C + D / E F
Inorder traversal â infix notation
A â B * C + D + E / F
Postorder traversal â postfix notation
A B C * â D E F / + +
26. Binary Search Tree â BST
⢠Trees can be used for sorting and searching data
⢠Search trees: general trees used for the purpose of searching
and sorting
⢠Binary search trees: binary trees used for the purpose of
searching and sorting
⢠A binary tree is a search tree if it is empty, or satisfies the
following:
â Every node has a key value that uniquely identifies it (i.e.
no two nodes have the same key)
â For every node, N, in the tree, the values of all the items in
its left subtree are smaller than the value in N, and the
values of all the items in its right subtree are larger than
the value in N.
28. Operations on Binary Search Tree
⢠The following are basic operations in binary search tree
â Findmin(tree) and Findmax(tree) â finds and returns the
position (or node) of the smallest and largest elements in the
tree, respectively.
â Insert (tree, x)- finds the appropriate position and inserts a
new node containing the key value x.
â Search (tree, x)-returns a pointer to the node in the tree that
has key value x, or NULL if there is no such key.
â Delete (tree, x) â finds the node containing x in the tree and
removes that node.
⢠Note that when a node is inserted or deleted from BST,
the definition of binary search tree should be preserved
29. C++ Implementation of Findmin and Findmax
node* findmax(node *T)
{
if (T!=NULL)
while(T->right!=NULL)
T=T->right;
return T;
}
node* findmin(node *T)
{
if (T!=NULL)
while (T->left!=NULL)
T=T->left;
return T;
}
30. Insertion in BST
⢠Suppose there is a binary search tree whose root node is
pointed to by RootPtr and we want to insert a node
(that stores x) pointed by NewNode. There are two
cases:
Case 1: There is no data in the tree (i.e. RootPtr is
NULL)
â The node pointed by NewNode should be made the
root node.
Case 2: There is data (i.e. RootPtr is NULL)
â Search the appropriate position, and insert the node
in that position.
31. Create the binary search tree using the following data elements
43, 10, 79, 90, 12, 54, 11, 9, 50
Insert 43 into the tree as the root of the tree.
Read the next element, if it is lesser than the root node element,
insert it as the root of the left sub-tree.
Otherwise, insert it as the root of the right of the right sub-tree.
⢠The process of creating BST by using the given elements, is
shown in the next slide.
32.
33. C++ Implementation insertion
void InsertBST(node *RNP, node *INP)
{//RNP=RootPtr and INP=NewNode
int Inserted=0;
while(Inserted = =0)
{
if(RNP->Num > INP->Num)
{
if(RNP->Left = = NULL)
{
RNP->Left = INP;
Inserted=1;
}
else
RNP = RNP->Left;
}
else
{
if(RNP->Right = = NULL)
{
RNP->Right = INP;
Inserted=1;
}
else
RNP = RNP->Right;
}
}//end of while
}
A recursive version of the function can
also be given as follows.
void InsertBST(node *RNP, node *INP)
{
if(RNP->Num>INP->Num)
{
if(RNP->Left==NULL)
RNP->Left = INP;
else
InsertBST(RNP->Left, INP);
}
else
{
if(RNP->Right==NULL)
RNP->Right = INP;
else
InsertBST(RNP->Right, INP);
}
}
34. Searching in BST
⢠To search a node (whose key value is x) in a binary
search tree (whose root node is pointed by RootPtr),
the following function return a pointer that points to
the node containing the element searched, or NULL
pointer if not found.
node *SearchBST (node *RootPtr, int x)
{
if((RootPtr = = NULL) || (RootPtr->Num = = x))
return(RootPtr);
else if(RootPtr->Num > x)
return(SearchBST(RootPtr->Left, x));
else
return(SearchBST (RootPtr->Right, x));
}
35. Deletion from a BST
⢠An algorithm for deleting a node from a binary search tree in such a way
that the remaining nodes still have the same inorder traversal:
â Leaves - these are the easiest, since all we need to do is delete the leaf and
set the pointer from its parent (if any) to NULL.
â Nodes with a single child - these too are fairly easy, since we just redirect
the pointer from the node's parent so that it points to the child.
â Nodes with both children - these can be fairly tricky, since we must
rearrange the tree to some extent. The method we shall use is to replace the
node being deleted by the rightmost node in its left sub tree. (We could
equally well have used the leftmost node in the right sub tree.) Because of
the rules for inorder traversals, this method guarantees the same traversal.
⢠Assuming the node to be deleted is present in the tree, we are faced with
two possibilities:
â the required node is the root node, or
â it is some other node.
⢠These must be treated as separate cases, since the root node has no
parent
36. C++ Implementation of node deletion
void DeleteBST (node *T, int x)
{ node *temp;
if (T==NULL)
cout<<â data not foundâŚâ;
else if (x<T->item)
T->left = DeleteBST (T->left, x);
else if (x>T->item)
T->right = DeleteBST (T->right, x);
else //node to be deleted found
{
if (T->left!=NULL && T->right!=NULL) //node having two children
{
temp = Findmin( T->right); //finds the smallest to the right of the node to be deleted.
T->item = temp->item; //copying smallest value to the node to be deleted
T->right = DeleteBST (T->right, T->item); //deletes the node containing smallest value.
}
else //one or zero child
{ temp = T;
if (T->left == NULL)
T = T->right;
else
if (T->right == NULL)
T = T->left;
delete (temp);
} }}
37. Sorting using Binary Search Tree
⢠One way that a binary search tree can be used
to sort data is as follows.
â E.g., Let us suppose that we have a list of integers,
such as 5, 2, 8, 4, and 1, that we wish to sort into
ascending order.
⢠We can perform a two-stage sorting algorithm.
â The first stage involves inserting the integers into a
binary search tree
â The second stage is performing inorder traversal
38. Sorting using Binary Search Tree
Stage 2: Inorder traversal - 1, 2, 4, 5, 8,
Stage 1: inserting the elements (5, 2, 8, 4, 1 )into
the BST one by one
39. Efficiency of Binary Search Trees
⢠The tree sort and tree search algorithms work well if
the initial data are in a jumbled order, since the binary
search tree will be fairly well balanced, which means
that there are roughly equal numbers of nodes in the
left and right subtree of any node.
⢠Trees that are wide and shallow have only a few levels,
so the insertion and searching routines have relatively
few steps.
⢠In fact, in these cases
â the sorting routine is O (n log n)
â the searching routine is essentially a binary search, and so is
O (log n).
Hinweis der Redaktion
Node(vertex) : an element in the tree, it maybe
labeled or not. e.g., b, e, g, âŚ