0% found this document useful (0 votes)
33 views71 pages

Binary Search Trees, Selection Trees Forests Representation of Disjoint Sets Counting Binary Trees

This document covers various tree data structures, focusing on Binary Search Trees (BST), their creation, searching, insertion, deletion, and operations like joining and splitting. It also discusses expression trees, how to construct them from postfix expressions, and the process of building binary trees from traversal pairs. Additionally, it introduces selection trees, specifically winner trees, and their application in merging ordered sequences.

Uploaded by

desaiyashwanth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views71 pages

Binary Search Trees, Selection Trees Forests Representation of Disjoint Sets Counting Binary Trees

This document covers various tree data structures, focusing on Binary Search Trees (BST), their creation, searching, insertion, deletion, and operations like joining and splitting. It also discusses expression trees, how to construct them from postfix expressions, and the process of building binary trees from traversal pairs. Additionally, it introduces selection trees, specifically winner trees, and their application in merging ordered sequences.

Uploaded by

desaiyashwanth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

MODULE 4

• Binary Search Trees,


• Selection Trees
• Forests
• Representation of Disjoint sets
• Counting Binary Trees
BINARY SEARCH TREE (BST)
• A binary search tree is a binary tree. it may be empty. If it is not empty
then, it satisfies the following properties:
1)Each node has exactly one key and the keys in the tree are distinct.
2)The keys in the left subtree are smaller than the key in the root.
3)The keys in the right subtree are larger than the key in the root.
4)The left and right subtrees are also binary search trees.

Fig(a) is not a Binary search tree fig(b) and (c) are Binary search trees
Creating a Binary Search Tree
• Now, let's see the creation of binary search tree using an example.
• Suppose the elements are - 45, 15, 79, 90, 10, 55, 12, 20, 50
• First, we have to insert 45 into the tree as the root of the tree.
• Then, read the next element; if it is smaller than the root node, insert it as
the root of the left subtree, and move to the next element.
• Otherwise, if the element is larger than the root node, then insert it as the
root of the right subtree.
• Step 1 - Insert 45
Step 2 - Insert 15.
• As 15 is smaller than 45, so insert it as the root node of the left subtree.

Step 3 - Insert 79.


• As 79 is greater than 45, so insert it as the root node of the right subtree.
Step 4 - Insert 90.
• 90 is greater than 45 and 79, so it will be inserted as the right subtree of 79.
Step 5 - Insert 10.
• 10 is smaller than 45 and 15, so it will be inserted as a left subtree of 15.
Step 6 - Insert 55.
• 55 is larger than 45 and smaller than 79, so it will be inserted as the left
subtree of 79.
Step 7 - Insert 12.
• 12 is smaller than 45 and 15 but greater than 10, so it will be inserted as the
right subtree of 10.
Step 8 - Insert 20.
• 20 is smaller than 45 but greater than 15, so it will be inserted as the right
subtree of 15.
Step 9 - Insert 50.
• 50 is greater than 45 but smaller than 79 and 55. So, it will be inserted
as a left subtree of 55.
Construct Binary Search Tree for the following:
(a) 13, 3, 4, 12, 14, 10, 5, 1, 8, 2, 7, 9, 11, 6, 18
(b) 43, 10, 79, 90, 12, 54, 11, 9, 50
(c) 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2
BST for (a)
1. Searching A Binary Search Tree
• Assume that we have to search for a node whose key value is
k. The search begins at the root (Program A and program B)
– If the root is NULL, then the tree contains no nodes and
hence the search is unsuccessful.
– If the key value k matches with the root's data then search
terminates successfully.
– If the key value is less than the root's data, then we should
search in the left subtree.
– If the key value is greater than the root's data, then we
should search in the right subtree.
Program A: recursive search algorithm for BST
Program B: Iterative search algorithm for BST
2. Inserting into a binary search tree
• Firstly verify, if the tree already contains the node with the
same data (Figure 27 &Program C).
• If the search is successful, then the new node cannot be
inserted into the binary search tree.
• If the search is unsuccessful, then we can insert the new node
at that point where the search terminated.

Figure 27: insertion of node 35 to existing BST


Program C: Node insertion to BST
3. Deletion from a binary search tree
• Deletion of a leaf: To delete 35 from the tree of figure 28, the
left-child field of its parent is set to NULL.
• Deletion of a non-leaf that has only one child: The node
containing the dictionary pair to be deleted is freed, and its
single-child takes the place of the freed node.
• So, to delete the 5 from the tree in figure 29, we simply change
the pointer from the parent node to the single-child node.
• The pair to be deleted is in a non-leaf node that has two
children: The pair to be deleted is replaced by either the
largest pair in its left subtree or the smallest one in its right
subtree. For instance, if we wish to delete the pair with key 30
from the tree in figure 28, then we replace it by key 5 as
shown in figure 29(b).
Figure 28: BST

Figure 29(a): node 5 deletion (b): node 30 deletion


4. Joining and splitting binary tree
There are two types of join operation on a binary search tree:
• ThreeWayJoin(small, mid, big): This creates a binary search
tree consisting of the pairs initially in the BST small and big as
well as pair mid.
• It is assumed that each key in small is smaller than mid key
and that each key in big is greater than mid key following the
join , both small and big are empty.
• TwoWayJoin(small, big): This joins the two binary search
tree small and big to obtain a single BST that contains all the
pairs originally in small and big.
• It is assumed that all keys of small are smaller than all keys of
big and that following the join both small and big are empty.
• split(theTree,k,small,big,mid): Splitting a binary search tree
will produce three trees: small, mid and big.
– If key is equal to root->data, then root->llink is the small,
root->data is mid & root->rlink is big.
– If key is lesser than the root->data, then the root's along
with its right subtree would be in the big.
– if key is greater than root->data, then the root’s along with
its left subtree would be in the small.
Application of Trees: EXPRESSION TREES
• Expression tree is a binary tree, because all of the operations are binary.
• It is also possible for a node to have only one child, as is the case with the
unary minus operator.
• The leaves of an expression tree are operands, such as constants or
variable names, and the other (non leaf) nodes contain operators.
• Once an expression tree is constructed we can traverse it in three ways:
• Inorder Traversal
• Preorder Traversal
• Postorder Traversal
Construction of expression tree
• An expression tree can be generated for the infix and postfix
expressions.
• An algorithm to convert a postfix expression into an expression tree is
as follows:
• Read the expression from left to right and one symbol at a time.

• If the symbol is an operand, we create a one-node tree and push a


pointer to it onto a stack.
• If the symbol is an operator, we pop pointers to two trees T1 and
T2 from the stack (T1 is popped first) and form a new tree whose
root is the operator and whose left and right children point to T2
and T1 respectively. A pointer to this new tree is then pushed onto
the stack.
Construct an expression tree for the postfix expression: a b + c d e + * *
• The first two symbols are operands, so we create one-node trees and push
pointers to them onto a stack.

• Next, a ‘+’ is read, so two pointers to trees are popped, a new tree is
formed, and a pointer onto the stack.

• Next, c, d, and e are read, and for each one-node tree is created and a
pointer to the corresponding tree is pushed onto the stack.

• Now a ‘+’ is read, so two trees are merged.


• Continuing, a ‘*’ is read, so we pop two tree pointers and form a new tree
with a ‘*’ as root.

• Finally, the last symbol is read, two trees are merged, and a pointer to the
final tree is left on the stack.
Construct expression tree for
a. 6 3 2 – 5 * + 2 $ 3 +
b. 3 4 + 5 6 ^ 7 / *
Building binary tree from traversal pair
• Sometimes it is required to construct a binary tree if its traversals are
known.
• From a single traversal it is not possible to construct unique binary tree.
• However any of the two traversals are given then the corresponding tree
can be drawn uniquely:
• Inorder and preorder,
• Inorder and postorder,
• Inorder and level order
• The basic principle for formulation is as follows:
– If the preorder traversal is given, then the first node is the root node.
– If the postorder traversal is given then the last node is the root node.
– Once the root node is identified, all the nodes in the left sub- trees
and right sub-trees of the root node can be identified using inorder.
– Same technique can be applied repeatedly to form sub-trees.
Example:
(A) Construct a binary tree from a given Preorder and Inorder
sequence
Inorder : 4, 2, 7, 5, 1, 8, 6, 3
Preorder: 1, 2, 4, 5, 7, 3, 6, 8

(B) Construct a binary tree from a given Postorder and Inorder


sequence
• Inorder : 3, 12, 6, 4, 7, 10, 11, 5, 2, 8
• Postorder: 3, 6, 7, 4, 12, 11, 8, 2, 5, 10
Solution Tree: A
Solution Tree: B
ADDITIONAL BINARY TREE OPERATIONS
1. Copying Binary Trees:-
• This function is a slightly modified version of postorder. Function which
returns an exact copy of the original tree:
treepointer copy(treepointer original)
{
treepointer temp;
if(original)
{
MALLOC(temp, sizeof(*temp));
temp->leftchild = copy(original->leftchild);
temp->rightchild= copy(original->rightchild);
temp->data = original->data;
return temp;
}
return NULL;
}
2. Testing Equality:-
• Equivalent binary trees have the same structure and the same information
in the corresponding nodes.
• By same structure, we mean that every branch in one tree corresponds to a
branch in the second tree. i.e the branching of the 2 trees is identical.
• This function returns TRUE if the two trees are equivalent and FALSE if
they are not.
int equal(treepointer first, treepointer second)
{
return(( !first && !second) || (first && second && (first->data ==
second->data) && equal(first->leftchild, second->leftchild) &&
equal (first->rightchild, second-> rightchild))
}
3. The Satisfiability Problem :
• Consider the formula that is constructed by set of variables: x1, x2,.., xn
and operators
Ù(and), Ú(or), ¬ (not).
• The variables can hold only of two possible values, true or false.

• The expression can form using these variables and operators is


defined by the following rules.
• A variable is an expression
• If x and y are expressions, then ¬x, xÙy, xÚy are expressions
• Parentheses can be used to alter the normal order of evaluation (¬
> Ù > Ú)
• Example:
x1 Ú (x2 Ù ¬ x3) If x1 and x3 are false and x2 is true
= false Ú (true Ù ¬false)
= false Ú true
= true
• The satisfiablity problem for formulas of the propositional calculus asks if
there is an assignment of values to the variable that causes the value of the
expression to be true.
• Let’s assume the formula in a binary tree
• (x1 Ù ¬ x2) Ú (¬ x1 Ù x3) Ú ¬ x3

• The inorder traversal of this tree is: x1 Ù ¬ x2 Ú ¬ x1 Ù x3 Ú ¬ x3


• The algorithm to determine satisfiablity is to let (x1, x2, x3) takes on all the
possible combination of true and false values to check the formula for
each combination.
• For n value of an expression, there are 2n possible combinations of true
and false
• For example n=3, the eight combinations are (t,t,t), (t,t,f), (t,f,t), (t,f,f),
(f,t,t), (f,t,f), (f,f,t), (f,f,f).
• To evaluate an expression, we traverse its tree in postorder,
• The node structure for this problem is
leftChild Data value rightChild

Node structure in C:
typedef enum {not, and, or, true, false} logical;
typedef struct node *treePointer;
typedef struct
{
treePointer leftChild;
logical data;
short int value;
treePointer rightChild;
}node;
• Assume that node->data contains the current value of the variable
represented at the leaf node. In the above tree, data field in x1, x2 and x3
contains either TRUE or FALSE.
• The first version of Satisfiability algorithm
The C function that evaluates the tree is modified version of postorder
traversal, given below:
void postordereval(treepointer node)
{
if( node)
{
postordereval(node->leftchild);
postordereval(node->rightchild);
switch( node->data) {
case not : node->value = ! node->rightchild->value;
break;
case and : node->value = node->rightchild->value &&
node->leftchild->value ; break;
case or : node->value = node->rightchild->value ||
node->leftchild->value ; break;
case true : node->value = TRUE; break;
case false : node->value = FALSE; break;
} } }
Selection Tree
• The Tournament tree is a complete binary tree with n external nodes and n
– 1 internal nodes.
• The external nodes represent the players, and the internal nodes are
representing the winner of the match between the two players. This tree is
also known as Selection tree.
• There are two types of Tournament Trees −
• Winner Tree
• Looser Tree
Winner Tree:
• Winner tree is a complete binary tree, in which each node is representing
the smaller or greater of its two children, is called winner tree.
• The root is holding the smallest or greatest node of the tree.
• The winner of the tournament tree is the smallest or greatest n key in all the
sequences.
• It is easy to see that winner tree can be formed in O(log n) time.
• Example − Suppose there are some keys, 3, 5, 6, 7, 20, 8, 2, 9

Winner Tree
• Suppose we have k ordered sequences, called runs, are to be merged into
single ordered sequence.

• Each run consists of some records and is in nondecreasing(ascending)


order of a designated field called the key.

• The merging task can be accomplished by repeatedly outputting the


record with the smallest key.

• The fig. illustrate a winner tree for the case k=8.


Winner Tree

fig.5.32
• The record pointed to by the root has the smallest key and so may be output.
• Now, the next record from run 4 enters the winner tree. It has a key value
15.
• To restructure the tree, the tournament has to be replayed only along the
path from node 11 to the root.
Looser Tree
• Looser Trees are complete binary tree for n players where n external nodes
and n – 1 internal nodes are present.
• The looser of the match is stored in the internal nodes. But in this overall
winner is stored at tree[0].
• The looser is an alternative representation, that stores the looser of a match
at the corresponding node.
• An advantage of the looser is that, to restructure the tree after winner tree
been output, it is sufficient to examine node on the path from leaf to root
rather than the sibling of the nodes on this path.
• To form a looser tree, we have to create winner tree at first.
• Suppose there are some keys, 10, 2, 7, 6, 5, 9, 12, 1.
• So we will create minimum winner tree at first.
Fig (b): Store looser of the
Fig (a): Minimum winner tree
match in each internal node
Loser tree corresponding to winner tree of fig 5.32
Forests
• A forest is a set of n>=0 disjoint trees.
• The concept of a forest is very close to that of a tree because if we remove
the root of a tree we obtain a forest.
• Ex: removing the root of any binary tree produces a forest of two trees.

Three tree forest


Transforming a forest into a binary tree
• To transform a forest into a single binary tree, we first obtain
the binary tree representation of each of the trees in the forest
and then link these binary trees together through the rightchild
field of the root nodes.

Binary tree representation of forest


Example 2
• We can define this transformation in a formal way as follows:
Definition:
• If T1, ….. Tn, is a forest of trees, then the binary tree
corresponding to this forest, denoted by B(T1,………, Tn):
• is empty, if n = 0 has root equal to root (T1);
• has left subtree equal to B(T11,T12,……T1m), where T11, T12,
……… T1m are the subtrees of root (T1); and has subtree B(T2,
….Tn).
Forest Traversal
• Preorder, Inorder, and Postorder traversals of the corresponding binary tree
T of a forest F have a natural correspondence with traversals on F.

PREORDER TRAVERSAL:
• The preorder traversal of T is equivalent to visiting the nodes of F in forest
preorder, which is defined as follows:
1. If F is empty, then return.
2. Visit the root of the first tree of F.
3. Traverse the subtrees of the first tree in tree preorder.
4. Traverse the remaining trees of F in preorder.
INORDER TRAVERSAL:
• Inorder traversal of T is equivalent to visiting the nodes of F in tree inorder,
which is defined as:
1. If F is empty, then return.
2. Traverse the subtrees of the first tree in tree inorder.
3. Visit the root of the first tree.
4. Traverse the remaining trees in tree inorder.
POSTORDER TRAVERSAL:
• There is no natural analog for the postorder traversal of the corresponding
binary tree of a forest. Nevertheless, we can define the postorder traversal
of a forest, F, as follows:
1. If F is empty, then return.
2. Traverse the subtrees of the first tree of F in tree postorder.
3. Traverse the remaining trees of F in tree postorder.
4. Visit the root of the first tree of F.
LEVEL ORDER TRAVERSAL:
• In a level order traversal of a forest, nodes are visited by level,
beginning with the roots of each tree in the forest.
• Withing each level, nodes are visited from left to right.
• The level order traversal of a forest and that of its associated
binary tree do not necessarily yield the same result.
Representation of Disjoint Sets:
• We study the use of trees in the representation of sets.
• We also assume that the sets being represented are pairwise disjoint, that is,
if and Si and Sj; are two sets and i ¹ j, then there is no element that is in
both Si, and Sj.
• For example, if we have 10 elements numbered 0 through 9, we may
partition them into three disjoint sets, S1={0,6,7,8), S2={1,4,9} and
S3={2,3,5}. Set Representation 239

• Figure shows one possible representation for these sets.

s s2 s3
1

Figure 5.39 : Possible forest representation of sets

(1) Disjoint set union. If S/ and Sy are two disjoint sets, then their union S, u Sy = {all
• The minimal operations that we can perform on these sets are:
• Disjoint set union: If Si and Sj are two disjoint sets, then their union Si È
Sj = {all elements x, such that x is in Si or Sj).

• Thus, Si È Sj={0, 6, 7, 8, 1, 4, 9}. Since we have assumed that all sets are
disjoint, following the union of Si and Sj we can assume that the sets Si and
Sj no longer exist independently. That is, we replace them by Si È Sj .
• Find(i): Find the set containing the element, i. For example, 3 is in set S3
and 8 is in set S1
5.10.1 Union And Find Operations
Union And Find Operations
• Let us consider
Suppose union
thatthewe operation
wish first. Suppose
to obtain that we
the union of wish to obtain
S1 and S2. the
Since of 5i
unionwe have
and 52- Since we have linked the nodes from children to parent, we simply make one of
linked the nodes from children to parent, we simply make one of the trees a
the trees a subtree of the other. Si u S2 could have either of the representations of Fig-
5.40. of the other. S1 È S2 could have either of the representations of
subtree
ure
figure.

u s2 or s2 u s1
Figure 5.40 : Possible representation of S j u S2
Possible representation of S1 È S2
Union – find functions
int SimpleFind (int i)
{
for(; parent [i] >= 0; i = parent [i] )
return i;
}
void SimpleUnion (int i, int j)
{
parent [i] = j;
}
o Find element i by simply following the parent value starting at i and continue until
we reach a negative parent parent value.

Ex: To find 5, we start at 5, and then move to 5’s parent, 2. since this node has a
negative parent value we have reached the root.

o The operation union (i, j) is equally simple. We pass in two trees with roots i and
j.

o Assuming that we adopt convention that the first tree becomes a subtree of the
second, the statement parent[i] = j accomplishes the union.
Weighting rule for union
Definition: Weighting rule for union(i, j). If the number of nodes in tree i is less
than the number in tree j then make j the parent of i; otherwise make i the parent of
j. The value count[i] will have the total number of nodes in the tree. Assign this
value to the root node and make it as negative to identify the root node of the tree.
void union2(int i, int j)
{
/* union the sets with roots i and j, i != j, using the weighting rule, parent[i] = -
count[i] and parent[j] = -count[j] */
int temp = parent[i] + parent[j];
if (parent[i] > parent[j]) {
parent[i] = j; /* make j the new root */
parent[j] = temp;
}
else {
parent[j] = i; /*make i the new root */
parent[i] = temp;
}
}
Consider the behaviour of weightedUnion on the following sequence of unions starting
from the initial configuration of parent[i] = -count[i]=-1, 0<=i<n=23.
Union(0,1) Union(2,3) Union(4,5) Union(6,7),Union(0,2) Union(4,6) Union(0,4).

The maximum level can be [log2m] +1, if the tree has m nodes.
Collapsing rule
Definition : If j is a node on the path from i to its root and parent[i] ≠
𝑟𝑜𝑜𝑡 𝑖 , then set parent[j] to root(i).
The following function incorporates the collapsing rule into the find operation.
The new function roughly doubles the time for an individual find. However, it
reduces the worst case time over a sequence of finds.

int find2(int i)
{
/* find the root of the tree containing element i. Use the
collapsing rule to collapse all nodes from i to root */
int root, trail, lead;
for (root=i; parent[root]>=0; root = parent[root])
for (trail = i; trail != root; trail=lead)
{
lead = parent[trail];
parent[trail] = root;
}
return root;
}
Application of Equivalence Classes
• Definition: A relation ≡ , over a set S, is said to be an equivalence relation
over S iff it is symmetric, reflexive and transitive over S.
• If an equivalence pair i ≡ j, is to be processed, we must first determine the
sets containing i and j.
• If these are different, then the two sets are to be replaced by their union.
• If the two sets are the same, then nothing is to be done, as the relation i ≡ j
is redundant; i and j are already in the same equivalence class.
• To process each equivalence pair we need to perform two finds and atmost
one union.
Counting Binary Trees:
Distinct Binary Trees:
We know that if n=0 or n=1,there is only one binary tree. If n=2, then there are
two distinct trees (Figure 5.45) and if n = 3, there are five such trees (Figure
5.46)
Stack Permutation:

• Using the concept of an inorder permutation, we can show that the number
of distinct permutations obtainable by passing the numbers 1 to n through a
stack and deleting in all possible ways is equal to the number of distinct
binary trees with n nodes.

• If we start with the numbers 1, 2, 3, then the possible permutations obtain


able by a stack are:

• (1, 2, 3) (1, 3, 2) (2, 1, 3) (2, 3, 1) (3, 2, 1)

• Each of these five permutations corresponds to one of the five distinct


binary trees with three nodes (Figure 5.51).

You might also like