id
int64
0
25.6k
text
stringlengths
0
4.59k
24,000
notes printf "\ /traverse the entire linked list *while !null printf "% " -data -link printf "\ /counts the number of nodes present in the linked list representing stack *count struct node int /traverse the entire linked list *while !null -link +return summary stack is linear data structure having very interesting property that an element can be inserted and deleted not at any arbitrary position but only at one end one en of stack remains sealed for insertion and deletion while the other end allows both the operations stack possesses lifo (last in first outproperty there are two basic methods for the implementation of stacks one where the memory is used statically and the other where the memory is used dynamically push is stack operation in which an element is added to stack pop is stack operation that removes an element from the stack stack is used to store return information in the case of function/procedure/subroutine calls henceone would find stack in architecture of any central processing unit (cpuin infix notation operators come in between the operands an expression can be evaluated using stack data structure keywords infixnotation of an arithmetic expression in which operators come in between their operands lifo(last in first outthe property of list such as stack in which the element which can be retrieved is the last element to enter it popstack operation retrieves value form the stack lovely professional university
24,001
postfixnotation of an arithmetic expression in which operators come after their operands notes prefixnotation of an arithmetic expression in which operators come before their operands pushstack operation which puts value on the stack stacka linear data structure where insertion and deletion of elements can take place only at one end self assessment choose the appropriate answers basic method of implementation of stack are(awhere the memory is used statically (bwhere the memory is used dynamically (cboth of the above (dnone of the above stack operation that removes an element from the stack (apop (bpush (clifo (dfifo the infix of particular element is what is the prefix of this (ax ( +xy (cxy(dnone of the above the hardware component known as an input device is(aram (bhard-disk (cmonitor (dprocessor (ekeyboard the hardware component known as an output device is(akeyboard (bmonitor (cram (dhard-disk (eprocessor cpu stands for (acontrol processing unit (bcentral processing unit (ccentral programming unit (dnone of these fill in the blanks stack is said to possess property is used to implement stacks where the memory is used statically pointers help in implementation of stacks in the operators come before operands lovely professional university
24,002
notes review questions write an algorithm to reverse an input string of characters using stack explain how function calls may be implemented using stacks for return values what are the advantages of implementing stack using dynamic memory allocation method trace the execution of infix-to-postfix algorithm on the following expression ( ( / one way to determine if string of characters is palindrome is to use one stack and one queue and to apply the following algorithm strategy(aput the input string on the stack and the queue simultaneously (bthuspopping the string from the stack is equivalent to reading it backwards while deleting the string from the queue is reading it forwards write program to implement stack of characters explain why we cannot use the following implementation for the method push in our linked stack error_code stack :push(stack_entry itemnode new_top(itemtop_node)top_node new_topreturn success what is wrong with the following attempt to use the copy constructor to implement the overloaded assignment operator for linked stackvoid stack :operator (const stack &originalstack new_copy(original)top_node new_copy top_nodehow can we modify this code to give correct implementationanswersself assessment ( ( ( ( ( ( lifo (last in first out array dynamic polish notation lovely professional university
24,003
further readings books notes brian kernighan and dennis ritchiethe programming languageprentice hall data structures and algorithmsshi-kuo changworld scientific data structures and efficient algorithmsburkhard monienthomas ottmannspringer kruse data structure program designprentice hall of indianew delhi mark allen welesdata structure algorithm analysis in second adition addison-wesley publishing rg dromeyhow to solve it by computercambridge university press shi-kuo changdata structures and algorithmsworld scientific sorenson and tremblayan introduction to data structure with algorithms thomas cormencharles eleiserson ronald rivestintroduction to algorithms prentice-hall of india pvt limitednew delhi timothy buddclassic data structures in ++addison wesley online links www en wikipedia org www web-source net www webopedia com lovely professional university
24,004
anil sharmalovely professional university unit queues notes contents objectives introduction queue model array implementation array-based implementation pointer-based implementation applications of queues summary keywords self assessment review questions further readings objectives after studying this unityou will be able todescribe queue model know array implementation describe various applications of queues introduction the queue abstract data type is also widely used one with applications very common in real life an example comes from the operating system software where the scheduler picks up the next process to be executed on the system from queue data structure in this unitwe would study the various properties of queuestheir operations and implementation strategies queue model queue is list of elements in which insertions are made at one end-called the rear and deletions are made from the other end-called the front this meansin particularthat elements are removed from queue in the same order as that in which they were inserted into the queue thusa queue exhibits the fifo (first in first outproperty the following are the allowed operations on queue insert(qe)this inserts an element into the queue delete(qae ethis deletes an element from the queue and stores it into empty(qae true/falsethis checks whether queue is empty or not lovely professional university
24,005
notes queue operations in pseudo-codeenqueue(qxq[tail[ ]< if tail[qlength[qthen tail[ < else tail[ <tail[ dequeue(qx < [head[ ]if head[qlength[qthen head[ < else head[ <head[ return these are also ( time operations figure shows the operations on queue figure operations on queue frontrear (aempty queue front rear (ba inserted front rear (cbc inserted front rear (da deleted front rear (eb deleted front rear (fd inserted lovely professional university
24,006
notes array implementation here toothere are two possible implementation strategies one where the memory is used statically and the other where memory is used dynamically array-based implementation to represent queue we require one-dimensional array of some maximum size say to hold the data items and two other variables front and rear to point to the beginning and the end of the queue hence queue data type may be defined in as followsstruct queue data[ ]int frontrearduring the initialization of queue qits front and rear are made to at each insertion to the queuewhich takes place at the rear end'rearis incremented by at each deletion'frontis incremented by the following procedures show the implementation of the queue operationsvoid insert(queue [] /this function inserts an element into the queue *if( rear =nprintf('queue is full!")else rear rear data[ rearxvoid delete(queue [] /*deletes an element from the queue and stores in *if( front = rearprintf("queue is empty!" front rear else frontq front = data[ front]boolean empty(queue [] lovely professional university
24,007
notes /this function checks if the queue is empty or not if( front = rearreturn(trueelse return(false)void initialize(queue []/this procedure initializes queue front rear an important point to be noticed in the above implementation is that the queue has tendency to move to the right unless occasionally 'frontcatches up with 'rearand both are reset to again (in the delete procedureas result it is possible that considerable portion of the elements array is free but the queue full signal is on to get rid of this problemwe may shift the elements array towards left by whenever deletion is made such shifting is time consuming since it has to be done for each deletion operation more efficient queue representation is obtained by regarding the array of elements of queue to be circular for easier algebraic manipulation we consider the array subscript ranging from - as beforerear will point to the element which is at the end of the queue the front points to one position anticlockwise to the beginning of the queue initiallyfront rear and front rear only if the queue is empty every insertion implies that the rear of the queue increases by except when rear - in that casethe rear is made zero if the queue is not full yet figure shows circular queue with elements where front= and rear= figure circular queue rear cc bb aa front lovely professional university
24,008
notes an implementation of the circular queue is shown belowstruct cqueue data[ ]int frontrearvoid insert(queue [] /this procedure inserts an element into the queue * rear ( rear nif( rear = frontprintf("queue full")else data[ rearxvoid delete(queue qt /deletes an element stores it in *if( front = rearprintf("queue empty")else data[ front] front =( frontlnboolean empty(queue []/this function checks if the queue is empty or not *if( front = rearreturn(true)else return(false)void initialize(queue []/this procedure initializes queue front rear in this implementationwe are using only - entries of the 'elementsarray to use all the elementsa special flag has to be maintained to distinguish between the queue_full and queue_ empty situations lovely professional university
24,009
pointer-based implementation notes as in stacksa queue could be implemented using linked list queue can be implemented by the following declarations and algorithmsstruct queuenode itemqueuenode *next}struct queuenode*front*rearvoid insert(queuenode *frontqueuenode *reart estruct queuenode *xx new(queuenode) ->item eif(front =nullfront xelse rear->next xrear xvoid delete(queuenode *frontt equeuenode *front/*this procedure deletes the element from the front of the queue stores it in *if(front =nullprintf("queue is empty")else front->itemfront front->nextif(front =nullrear nullboolean empty(queuenode * /check if queue is emptyif( =nullreturn(trueelse return(false)void initialize(queuenode *frontqueuenode *rearfront nullrear nulltask write program to implement circular queue lovely professional university
24,010
notes applications of queues one major application of the queue data structure is in the computer simulation of real-world situation queues are also used in many ways by the operating systemthe program that schedules and allocates the resources of computer system one of these resources is the cpu (central processing unititself if you are working on multi-user system and you tell the computer to run particular programthe operating system adds your request to its "job queuewhen your request gets to the front of the queuethe program you requested is executed similarlythe various users for the system must share the / devices (printersdisks etc each device has its own queue of requests to printread or write to these devices the following subsection discusses one application of the queues the priority queue it is used in time-sharing multi-user systems where programs of high priority are processed first arid programs with the same priority form standard queue priority queues priority queue is collection of elements such that each element has been assigned priority and such that the order in which elements are deleted and processed is defined by the following rulesan element of higher priority is processed before any element of lower priority two elements with the same priority are processed according to the order in which they were inserted into the queue we would use singly linked list to implement the priority queue each node of the linked list would have type definition as followsstruct qelement itemint priorityqelement *next*pqueue*front*rearthe algorithm for the insertion would change now insertion would insert the new element at the correct position according to the priority of the element the elements of the priority queue would be sorted in non-descending order of the priority with the front of the queue having the element with the highest priority the deletion procedure need not change since the element at the front is the one with the highest priority and that is the one that should be deleted void insert(pqueue *frontpqueue *reart eint /this inserts an element having data and priority into the priority queue */*the insertion maintains the sorted order of the priority queue *pqueue * *rpqueue *xint prx new(pqueue) ->item ex->priority lovely professional university
24,011
notes if(front =nullfront xx->next nullrear / is the first node being added to the priority queue*elseif(front->priority px->next frontfront / has the highest priority hence should be at the front*elseif(rear->priority px->next nullrear->next xrear / has the least priority hence should be at the rear*else / has to be inserted in between according to its priority* frontpr ->prir nullwhile(pr /advance through the queue till the proper position is reached * ->nextr fpr ->priority/ now points to the node before which has to be inserted and points to the node which should be before * ->next xx->next ftask write an implementation of the extended_queue method full in light of the simplicity of this method in the linked implementationwhy is it still important to include it in the linked class extended_queuelovely professional university
24,012
notes case study convert an infix expression to prefix form #include #include #include #define typedef enum {falsetruebool#include "stack #include "queue #define nops char operators ["()^/*+-"int priorities[{ , , , , , , }char associates[rllll"char [ ]char *tptr /this is where prefix will be saved int getindexchar op /returns index of op in operators *int ifori= <nops++ ifoperators[ =op return ireturn - int getprioritychar op /returns priority of op *return prioritiesgetindex(op]char getassociativitychar op /returns associativity of op *return associatesgetindex(op]void processopchar opqueue *qstack * /contd lovely professional university
24,013
notes performs processing of op *switch(opcase ')'printf"\ pushing \ )spushsop )breakcase '('while!qempty( *tptr+qpop( )printf"\tq popping % \ "*(tptr- )while!sempty(schar popop spop( )printf"\ts popping % \ "popop )ifpopop =')break*tptr+popopbreakdefaultint priop/priority of op char topop/operator on stack top int pritop/priority of topop char asstop/associativity of topop while!sempty(spriop getpriority(op)topop stop( )pritop getpriority(topop)asstop getassociativity(topop)ifpritop priop |(pritop =priop &asstop =' '|topop =')/imp breakwhile!qempty( *tptr+qpop( )printf"\tq popping % \ "*(tptr- )*tptr+spop( )printf"\ts popping % \ "*(tptr- )contd lovely professional university
24,014
notes printf"\ts pushing % \ "op )spushsop )breakbool isopchar op /is op an operator*return (getindex(op!- )char *in prechar *str /returns valid infix expr in str to prefix *char *sptrqueue {null}stack nullchar *res (char *)mallocn*sizeof(char)char *resptr restptr tforsptr=str+strlen(str)- sptr!=str- -sptr printf"processing % tptr- =% \ "*sptrtptr- )ifisalpha(*sptr/if operand qpush& *sptr )else ifisop(*sptr/if valid operator processop*sptr& & )else ifisspace(*sptr/if whitespace else fprintfstderr"error:invalid char % \ "*sptr )return ""while!qempty(& *tptr+qpop(& )printf"\tq popping % \ "*(tptr- )while!sempty(& *tptr+spop(& )printf"\ts popping % \ "*(tptr- )contd lovely professional university
24,015
notes *tptr printf" =% \ " )for-tptrtptr!= - -tptr *resptr+*tptr*resptr return resint main(char [ ]puts"enter infix freespaces max )gets( )while(*sputsin pre( )gets( )return explanation in an infix expressiona binary operator separates its operands ( unary operator precedes its operandin postfix expressionthe operands of an operator precede the operator in prefix expressionthe operator precedes its operands like postfixa prefix expression is parenthesis-freethat isany infix expression can be unambiguously written in its prefix equivalent without the need for parentheses to convert an infix expression to reverse-prefixit is scanned from right to left queue of operands is maintained noting that the order of operands in infix and prefix remains the same thuswhile scanning the infix expressionwhenever an operand is encounteredit is pushed in queue if the scanned element is right parenthesis (')')it is pushed in stack of operators if the scanned element is left parenthesis ('(')the queue of operands is emptied to the prefix outputfollowed by the popping of all the operators up tobut excludinga right parenthesis in the operator stack if the scanned element is an arbitrary operator othen the stack of operators is checked for operators with greater priority then such operators are popped and written to the prefix output after emptying the operand queue the operator is finally pushed to the stack when the scanning of the infix expression is completefirst the operand queueand then the operator stackare emptied to the prefix output any whitespace in the infix input is ignored thus the prefix output can be reversed to get the required prefix expression of the infix input question write program to implement queue by using an array lovely professional university
24,016
notes summary queue is list of elements in which insertions are made at one end called the rear and deletions are made from the other end called the front queue exhibits the fifo (first in first outproperty to represent queue we require one-dimensional array of some maximum size say to hold the data items and two other variables front and rear to point to the beginning and the end of the queue as in stacksa queue could be implemented using linked list one major application of the queue data structure is in the computer simulation of real-world situation queues are also used in many ways by the operating systemthe program that schedules and allocates the resources of computer system each device has its own queue of requests to printread or write to these devices priority queue is collection of elements such that each element has been assigned priority an element of higher priority is processed before any element of lower priority two elements with the same priority are processed according to the order in which they were inserted into the queue keywords fifo(first in first outthe property of linear data structure which ensures that the element retrieved from it is the first element that went into it frontthe end of queue from where elements are retrieved queuea linear data structure in which the element is inserted at one end while retrieved from another end rearthe end of queue where new elements are inserted self assessment choose the appropriate answer priority queue is (acollection of elements such that each element has been assigned priority (bcollection of / devices (ccollection of fifo (dnone of the above every insertion implies that the rear of the queue increases by except when rear (an- (bn- (cn- (dn- fill in the blanks during the initialization of queue qits front and rear are made to lovely professional university
24,017
more efficient queue representation is obtained by regarding the array of elements of queue to be queue could be implemented using reverse polish notation is also called is used in time-sharing multi-user systems where programs of high priority are processed first amid programs with the same priority form standard queue queue exhibits the property queue could be implemented using and is collection of elements such that each element has been assigned priority notes review questions write segment of code to create copy of given queue let be the given queue and be the copy all the elements of must be equal to do not assume any implementation of queue describe the application of queue how will you insert and delete an element in queue write program to implement double-ended queuewhich is queue in which insertions and deletions may be performed at either end use linked representation write the following methods for linked queues(athe method empty(bthe method retrieve(cthe destructor(dthe copy constructor(ethe overloaded assignment operator assemble specification and method filescalled queue and queue cfor linked queuessuitable for use by an application program for linked extended_queuethe function size requires loop that moves through the entire queue to count the entriessince the number of entries in the queue is not kept as separate member in the class consider modifying the declaration of linked extended_ queue to add count data member to the class what changes will need to be made to all the other methods of the classdiscuss the advantages and disadvantages of this modification compared to the original implementation write an implementation of the extended_queue method full in light of the simplicity of this method in the linked implementationwhy is it still important to include it in the linked class extended_queue give formal definition of the term dequeusing the definitions given for stack and queue as models recall that entries may be added to or deleted from either end of dequebut nowhere except at its ends give two reasons why dynamic memory allocation is valuable lovely professional university
24,018
notes answersself assessment ( ( circular linked list postfix notation priority queue fifo (first in first out arraylinked list priority queue further readings books brian kernighan and dennis ritchiethe programming languageprentice hall data structures and algorithmsshi-kuo changworld scientific data structures and efficient algorithmsburkhard monienthomas ottmannspringer kruse data structure program designprentice hall of indianew delhi mark allen welesdata structure algorithm analysis in second adition addison-wesley publishing rg dromeyhow to solve it by computercambridge university press shi-kuo changdata structures and algorithmsworld scientific sorenson and tremblayan introduction to data structure with algorithms thomas cormencharles eleiserson ronald rivestintroduction to algorithms prentice-hall of india pvt limitednew delhi timothy buddclassic data structures in ++addison wesley online links www en wikipedia org www web-source net www webopedia com lovely professional university
24,019
unit trees unit trees notes contents objectives introduction concept of tree binary tree types of binary tree properties of binary tree binary representation implementation of binary tree binary tree traversal order of traversal of binary tree procedure for inorder traversal summary keywords self assessment review questions further readings objectives after studying this unityou will be able todiscuss the concept of tree explain concept of binary tree know binary tree traversal introduction while dealing with many problems in computer scienceengineering and many other disciplinesit is needed to impose hierarchical structure on collection of data items for examplewe need to impose hierarchical structure on collection of data items while preparing organizational charts and genealogiesto represent the syntactic structure of source programs in compilers tree is data structure that is used to model such hierarchical structure on data itemshence the study of tree as one of the data structures is important this module discusses tree as data structure lovely professional university
24,020
notes concept of tree tree is set of one or more nodes such that there is specially designated node called rootand remaining nodes are partitioned into > disjoint set of nodes ,tn each of which is tree shown below in figure is structurewhich is tree figure tree structure this is tree because it is set of nodes {abcdefghi}with node as root nodeand the remaining nodes are partitioned into three disjoint sets{bghi}{cefand {drespectively each of these sets is tree individually because each of these sets satisfies the above properties shown below in figure is structurewhich is not treefigure non-tree structure this is not tree because it is set of nodes {abcdefghi}with node as root nodebut the remaining nodes cannot be partitioned into disjoint setsbecause the node is shared given below are some of the important definitionswhich are used in connection with trees degree of node of treethe degree of node of tree is the number of sub-trees having this node as rootor it is number of decedents of node if degree is zero then it is called terminal node or leaf node of tree degree of treeit is defined as the maximum of degree of the nodes of the treei degree of tree max (degree (node ifor to level of nodewe define the level of the node by taking the level of the root node to be and incrementing it by as we move from the root towards the sub-trees the level of all the descendents of the root nodes will be the level of their descendents will be and so on we then define depth of the tree to be the maximum value of level for node of tree lovely professional university
24,021
notes consider the tree given in figure figure the degree of each node of the treenode degree the degree of the treemaximum (degree of all the nodes the level of nodes of the treenode task level in figure calculate the degree of true binary tree binary tree is special tree where each non-leaf node can have atmost two child nodes most important types of trees which are used to model yes/noon/offhigher/loweri binary decisions are binary trees recursive definition" binary tree is either empty or node that has left and right sub-trees that are binary trees empty trees are represented as boxes (but we will almost always omit the boxes)lovely professional university
24,022
notes in formal waywe can define binary tree as finite set of nodes which is either empty or partitioned in to sets of tltrwhere is the root and tl and tr are left and right binary treesrespectively figure binary tree structure sofor binary tree we find that the maximum number of nodes at level will be - if is the depth of the tree then the maximum number of nodes that the tree can have is - - types of binary tree there are two main binary tree and these are full binary tree complete binary tree full binary tree full binary tree is binary of depth having nodes if it has it is not full binary tree examplefor the number of nodes full binary tree with depth is shown in figure full binary tree we use numbers from to as labels of the nodes of the tree if binary tree is fullthen we can number its nodes sequentially fom to - starting from the root nodeand at every level numbering the nodes from left to right lovely professional university
24,023
complete binary tree notes complete binary tree of depth is tree with nodes in which these nodes can be numbered sequentially from to nas if it would have been the first nodes in full binary tree of depth complete binary tree with depth is shown in figure figure complete binary tree properties of binary tree main properties of binary tree are if binary tree contains nodesthen it contains exactly edges binary tree of height has nodes or less if we have binary tree containing nodesthen the height of the tree is at most and at least ceiling log ( if binary tree has nodes at level thenit has at most nodes at level the total number of nodes in binary tree with depth (root has depth zerois + task in figure total no of node present binary representation if binary tree is complete binary treeit can be represented using an array capable of holding elements where is the number of nodes in complete binary tree if the tree is an array of elementswe can store the data values of the ith node of complete binary tree with nodes at an index in an array tree that means we can map node to the ith index in the arrayand the parent of node will get mapped at an index / whereas the left child of node gets mapped at an index and the right child gets mapped at an index examplea complete binary tree with depth having the number of nodes can be represented using an array of as shown in figure lovely professional university
24,024
notes array tree an array representation of complete binary tree having nodes and depth shown in figure is another example of an array representation of complete binary tree with depth with the number of nodes array tree an array representation of complete binary tree with nodes and depth in generalany binary tree can be represented using an array we see that an array representation of complete binary tree does not lead to the waste of any storage but if you want to represent binary tree that is not complete binary tree using an array representationthen it leads to the waste of storage as shown in figure figure an array representation of binary tree array tree an array representation of binary tree is not suitable for frequent insertions and deletionseven though no storage is wasted if the binary tree is complete binary tree it makes insertion lovely professional university
24,025
and deletion in tree costly thereforeinstead of using an array representationwe can use linked representationin which every node is represented as structure with three fieldsone for holding dataone for linking it with the left subtreeand the third for linking it with right subtree as shown herenotes leftchild data rightchild we can create such structure using the following declarationstruct tnode int data struct tnode *lchild,*rchild} tree representation that uses this node structure is shown in figure figure linked representation of binary tree null null null null null implementation of binary tree like general treebinary trees are implemented through linked lists typical node in binary tree has structure as follows (refer to figure )struct node struct node *leftchildint nodevalue/this can be of any data type *struct node *rightchild}figure node structure of binary tree left child value right child the 'left child'and 'right childare pointers to another tree-node the "leaf node(not shownhere will have null values for these pointers the binary tree creation follows very simple principle for the new element to be addedcompare it with the current element in the tree if its value is less than the current element in the treethen move towards the left side of that element or else to its right if there is no sub tree on lovely professional university
24,026
notes the leftthen make your new element as the left child of that current element or else compare it with the existing left child and follow the same rule exactlythe same has to done for the case when your new element is greater than the current element in the tree but this time with the right child though this logic is followed for the creation of binary treethis logic is often suitable to search for key value in the binary tree algorithm for the implementation of binary tree step- if value of new element current elementthen go to step- or else step- step- if the current element does not have left sub-treethen make your new element the left child of the current elementelse make the existing left child as your current element and go to step- step- if the current element does not have right sub-treethen make your new element the right child of the current elementelse make the existing right child as your current element and go to step- task "if binary tree is complete binary treeit can be represented using an array capable of holding elements where is the number of nodes in complete binary tree discuss lab exercise programdepicts the segment of code for the creation of binary tree struct node struct node *leftint valuestruct node *right}create_tree(struct node *currstruct node *new if(new->value valueif(curr->left !nullcreate_tree(curr->leftnew)else curr->left newelse if(curr->right !nullcreate_tree(curr->rightnew)else lovely professional university
24,027
notes curr->right newprogrambinary tree creation array-based representation of binary tree consider complete binary tree having nodes where each node contains an item (valuelabel the nodes of the complete binary tree tht from top to bottom and from left to right - associate with the array where the entry of is the item in the node labelled of ti - figure depicts the array representation of binary tree of figure given the index of nodewe can easily and efficiently compute the index of its parent and left and right childrenindex of parent( )/ index of left child index of right child table array representation of binary tree item left child right child - - node - - - - - - - - first column represents index of nodesecond column consist of the item stored in the node and third and fourth columns indicate the positions of left and right children (- indicates that there is no child to that particular node binary tree traversal this section discusses different orders in which binary tree can be traversed the algorithms for some commonly used orders of traversal are also presented it also discusses the issue of construction of unique binary tree given the orders of traversal order of traversal of binary tree the following are the possible orders in which binary tree can be traversed ldr lrd dlr rdl rld drl lovely professional university
24,028
notes wherel stands for traversing the left sub-treer stands for traversing the right sub-treeand stands for processing the data of the node thereforethe order ldr is the order of traversal in which we start with the root nodevisit the left sub-tree firstthen process the data of the root nodeand then go for visiting the right subtree since the leftas well as right sub-trees are also the binary treesthe same procedure is used recursively while visiting the left and right sub-trees the order ldr is called inorderthe order lrd is called postorderand the order dlr is called preorder the remaining three orders are not used if the processing that we do with the data in the node of tree during the traversal is simply printing the data valuethen the output generated for tree given below in figure using the inorderpreorder and postorder is the one shown below in figure itself figure binary tree along with its inorderpreorder and postorder different order path in figure areinorderdbheiafcg preorderabdehicfg postorderdhiebfgca if an expression is represented as binary tree then the inorder traversal of the tree gives us an infix expressionwhereas the postorder traversal gives us posfix expression as shown below in figure figure binary tree of an expression along with its inorder and postorder lovely professional university
24,029
notes different order path in figure areinorder postorderabc*+de*given an order of traversal of tree it is possible to construct tree exampleconsider the following orderinorder dbeac we can construct the binary trees shown below in figure using this order of traversala binary trees constructed using given inorder therefore we conclude that given only one order of traversal of tree it is possible to construct number of binary treesa unique binary tree is not possible to be constructed for construction of unique binary tree we require two orders in which one has to be inorderthe other can be preorder or postorder exampleconsider the following orderslnorder dbeac postorder debca we can construct unique binary tree shown in figure using these orders of traversal lovely professional university
24,030
notes unique binary constructed using the inorder and postorder procedure for inorder traversal void inorder(tnode *pif( !nullinorder( ->lchild)printf( ->data)inorder( ->rchild) non-recursive/iterative procedure for traversing binary tree in inorder is given below for the purpose of doing the analysis void inorder(tnode *ptnode *stack[ ]int toptop if( !nulltop top stack[toppp ->lchildwhile(top while( !null/*push the left child onto the stack*top top stack[toppp ->lchild lovely professional university
24,031
notes stack[top]top top-lprintf( ->data) ->rchildif( !null/*push right child*top top+ stack[toppp ->lchildanalysis consider the iterative version of the inorder given above if the binary tree to be traversed is having nodesthen the number of nil links is since every node is placed on the stack oncethe statements stack[top: and :stack[topare executed times the test for nil links will be done exactly times so every step will be executed no more than some small constant times nhence the order of algorithm (nsimilar analysis can be done to obtain the estimate of the computation time for preorder and post order preorder traversal void preorder(tnode *pif( !nullprintf( ->data)preorder( ->lchild)preorder( ->rchild)postorder traversal void postorder(tnode *pif(!ppostorder( ->lchild)postorder( ->rchild)printf( ->data)lovely professional university
24,032
notes consider the following example given the preorder and inorder traversal of binary tree draw the tree and write down its postorder traversal inorderzaqpyxcb preorderqazypcxb to obtain the binary tree take the first node in preorderit is root nodewe then search for this node in the inorder traversalall the nodes to the left of this node in the inorder traversal will be the part of the left sub-treeand all the nodes to the right of this node in the inorder traversal will be the part of the right sub-tree we then consider the next node in the preoderif it is part of the left sub-treethen we make it as left child of the roototherwise if it is part of the right sub-tree then we make it as part of right sub-tree this procedure is repeated recursively to get the tree shown below in figure figure unique binary tree constructed using the inorder and postorder the post order for this tree iszapxbcyq the following function counts the number of leaf node in binary tree int count(tnode *pif( =nullcount else if(( -> child =null&( ->rchild =null)count else count count( -> childcount( ->rchild)the following procedure swaps the left and the right child of every node of given binary tree void swaptree(tnode * lovely professional university
24,033
notes tnode *tempif( !nullswaptree( -> child)swaptree( ->rchild)temp -> childp-> child ->rchildp->rchild tempthe following function checks whether the two binary trees are equal or not boolean equal(tnode * tnode * boolean ansif(( =null&( =null)ans trueelse if((( ==null)&&( !=null))||(( !=null)&&( ==null))ans falseelse while(( !null&( !null)if( !null&( !null)if((equal( -> child, -> child)ans equal( ->rchild, ->rchild)else ans falseelse ans falsereturn(ans)the following function creates exact copy of given binary trees tnode *copytree(tnode *ptnode *qif( =nullreturn(null)else lovely professional university
24,034
notes new(tnode) ->data ->dataq->lchild copytree( ->lchild) ->rchild copytree( ->rchild)return( ) summary tree is set of one or more nodes such that there is specially designated node called rootand remaining nodes are partitioned into disjoint set of nodes the degree of node of tree is the number of sub-trees having this node as rootor it is number of decedents of node if degree is zero then it is called terminal node or leaf node of tree degree of tree is defined as the maximum of degree of the nodes of the tree tree non of whose nodes has more than children is known as -ary tree in other wordsan -ary tree is tree whose degree is at the most binary tree is special type of tree having degree binary tree of depth can have maximum - number of nodes if binary tree has fewer than - nodesit is not full binary tree keywords degree of treethe highest degree of node appearing in the tree inordera tree traversing method in which the tree is traversed in the order of left-treenode and then right-tree level of nodethe number of nodes that must be traversed to reach the node from the root nodea data structure that holds information and links to other nodes postordera tree traversing method in which the tree is traversed in the order of left-treerighttree and then node preordera tree traversing method in which the tree is traversed in the order of nodeleft-tree and then right-tree root nodethe node in tree which does not have parent node treea two-dimensional data structure comprising of nodes where one node is the root and rest of the nodes form two disjoint sets each of which is tree lovely professional university
24,035
self assessment notes in the context of the figure given below give the answers of self assessment what is the degree of node ( ( ( ( what is the degree of node ( ( ( ( what is the level of node ( ( ( ( what is the level of node ( ( ( ( fill in the blanks to delete node from binary search tree the method to be used depends on the order ldr is called the order lrd is called and the order dlr is called binary tree is special type of tree having degree degree three tree is called tree node with degree zero is called node state the following statements are true or false binary tree of depth can have maximum - number of nodes for binary treemaximum number of nodes at level is * - full binary tree is binary of depth having nodes if it has it is not full binary tree review questions give the array representation of complete binary tree with depth having the number of nodes lovely professional university
24,036
notes how many binary trees are possible with three nodes construct binary tree whose in-order and pre-order traversal is given below in-order , , , , , , , , pre-order , , , , , , , , what do you mean by binary treealso explain the various properties of binary tree consider the tree given below(afind the degree of each mode of the tree (bthe degree of the tree (cthe level of each nodes of the tree determine the order in which the vertices of the binary tree given in question no will be visited under(ainorder (bpreorder (cpostorder write program to delete all the leaf nodes of binary tree write method and the corresponding recursive function to count the leaves ( the nodes with both subtrees emptyof linked binary tree write method and the corresponding recursive function to insert an entrypassed as parameterinto linked binary tree if the root is emptythe new entry should be inserted into the roototherwise it should be inserted into the shorter of the two subtrees of the root (or into the left subtree if both subtrees have the same height write function to perform double-order traversal of binary treemeaning that at each node of the treethe function first visits the nodethen traverses its left subtree (in double order)then visits the node againthen traverses its right subtree (in double orderanswersself assessment ( ( ( ( number of children for the node to be deleted lovely professional university
24,037
inorderpostorderpreorder ternary terminal/leaf true true true notes further readings books brian kernighan and dennis ritchiethe programming languageprentice hall data structures and algorithmsshi-kuo changworld scientific data structures and efficient algorithmsburkhard monienthomas ottmannspringer kruse data structure program designprentice hall of indianew delhi mark allen welesdata structure algorithm analysis in second adition addison-wesley publishing rg dromeyhow to solve it by computercambridge university press shi-kuo changdata structures and algorithmsworld scientific sorenson and tremblayan introduction to data structure with algorithms thomas cormencharles eleiserson ronald rivestintroduction to algorithms prentice-hall of india pvt limitednew delhi timothy buddclassic data structures in ++addison wesley online links www en wikipedia org www web-source net www webopedia com lovely professional university
24,038
mandeep kaurlovely professional university unit binary search tree and avl trees notes contents objectives introduction binary search tree counting the number of nodes in binary search tree searching for target key in binary search tree deletion of node from binary search tree deletion of node with two children deletion of node with one child deletion of node with no child application of binary search tree avl tree summary keywords self assessment review questions further readings objectives after studying this unityou will be able toz describe binary search tree explain deletion of node with two child and with single child describe applications of bst introduction consider the problem of searching linked list for some target key there is no way to move through the list other than one node at timeand hence searching through the list must always reduce to sequential search as you knowsequential search is usually very slow in comparison with binary search henceassuming we can keep the keys in ordersearching becomes much faster if we use contiguous list and binary search suppose we also frequently need to make changes in the listinserting new entries or deleting old entries binary search tree binary search tree is binary tree which may be emptyand every node contains an identifier and identifier of any node in the left sub-tree is less than the identifier of the root identifier of any node in the right sub-tree is greater than the identifier of the root and the left sub-tree as well as right sub-tree both are binary search trees lovely professional university
24,039
notes tree shown below in figure is binary search treefigure binary search tree binary search tree is basically binary treeand therefore it can be traversed is inorderpreorderand postorder if we traverse binary search tree in inorder and print the identifiers contained in the nodes of the treewe get sorted list of identifiers in the ascending order binary search tree is an important search structure for exampleconsider the problem of searching list if list is an ordered then searching becomes fasterif we use contiguous list and binary searchbut if we need to make changes in the list like inserting new entries and deleting old entries then it is much slower to use contiguous list because insertion and deletion in contiguous list requires moving many of the entries every time so we may think of using linked list because it permits insertions and deletions to be carried out by adjusting only few pointersbut in linked list there is no way to move through the list other than one node at time hence permitting only sequential access binary trees provide an excellent solution to this problem by making the entries of an ordered list into the nodes of binary search treewe find that we can search for key in ( log nsteps creating binary search tree we assume that every node binary search tree is capable of holding an integer data item and the links which can be made pointing to the root of the left and the right sub-tree respectively therefore the structure of the node can be defined using the following declarationstruct tnode int datatnode *lchidtnode *rchildto create binary search tree we use procedure named insert which creates new node with the data value supplied as parameter to itand inserts into an already existing tree whose root pointer is also passed as parameter the procedure accomplishes this by checking whether the tree whose root pointer is passed as parameter is empty if it is empty then the newly created node is inserted as root node if it is not empty then it copies the root pointer into variable temp it then stores value of temp in another variable temp compares the data value of the node pointed to by temp with the data value supplied as parameterif the data value supplied as parameter is smaller than the data value of the node pointed to by temp then it copies the left link of the node pointed by temp into temp (goes to the left)otherwise it copies the right link of the node pointed by temp into temp (goes to the rightit repeats this process till temp becomes nil lovely professional university
24,040
notes when temp becomes nilthe new node is inserted as left child of the node pointed to by temp if data value of the node pointed to by temp is greater than data value supplied as parameter otherwise the new node is inserted as right child of node pointed to by temp therefore the insert procedure is void insert(tnode *pint valtnode *temp *temp if ( =nullp new(tnode) ->data valp-> child nullp->rchild nullelse temp pwhile(temp !nulltemp temp if(temp ->data valtemp temp -> eftelse temp temp ->rightif(temp ->data valtemp ->left new(tnode)temp temp ->lefttemp ->data valtemp ->left nulltemp ->rightnullelse temp ->right new(tnode)temp temp ->righttemp ->data valtemp ->left nulltemp ->right null lovely professional university
24,041
counting the number of nodes in binary search tree notes counting the number of nodes in given binary treethe tree is required to be traversed recursively until leaf node is encountered when leaf node is encountereda count of is returned to its previous activation (which is an activation for its parent)which takes the count returned from both the children' activationadds to itand returns this value to the activation of its parent this waywhen the activation for the root of the tree returnsit returns the count of the total number of the nodes in the tree lab exercise programa complete program to count the number of nodes is as follows#include #include struct tnode int datastruct tnode *lchild*rchild}int count(struct tnode *pifp =nullreturn( )else ifp->lchild =null & ->rchild =nullreturn( )else return( (count( ->lchildcount( ->rchild)))struct tnode *insert(struct tnode * ,int valstruct tnode *temp ,*temp if( =nullp (struct tnode *malloc(sizeof(struct tnode))/insert the new node as root node*if( =nullprintf("cannot allocate\ ")exit( ) ->data valp->lchild= ->rchild=nulllovely professional university
24,042
notes else temp /traverse the tree to get pointer to that node whose child will be the newly created node*while(temp !nulltemp temp iftemp ->data valtemp temp ->lchildelse temp temp ->rchildiftemp ->data valtemp ->lchild (struct tnode*)malloc(sizeof(struct tnode))*inserts the newly created node as left child*temp temp ->lchildif(temp =nullprintf("cannot allocate\ ")exit( )temp ->data valtemp ->lchild=temp ->rchild nullelse temp ->rchild (struct tnode*)malloc(sizeof(struct tnode));*inserts the newly created node as left child*temp temp ->rchildif(temp =nullprintf("cannot allocate\ ")exit( )temp ->data valtemp ->lchild=temp ->rchild null lovely professional university
24,043
notes return( )/ function to binary tree in inorder *void inorder(struct tnode *pif( !nullinorder( ->lchild)printf("% \ ", ->data)inorder( ->rchild)void main(struct tnode *root nullint ,xprintf("enter the number of nodes\ ")scanf("% ",& )whilen -- printf("enter the data value\ ")scanf("% ",& )root insert(root, )inorder(root)printf("\nthe number of nodes in tree are :% \ ",count(root))input the number of nodes the created tree should have the data values of the nodes in the tree to be created are output the number of nodes in the tree is searching for target key in binary search tree searching for the key in the given binary search treestart with the root node and compare the key with the data value of the root node if they matchreturn the root pointer if the key is less than the data value of the root noderepeat the process by using the left subtree otherwiserepeat the same process with the right subtree until either match is found or the subtree under consideration becomes an empty tree lovely professional university
24,044
notes boolean search(tnode *pint valboolean anstnode *temptemp pans falsewhile ((temp !null&(!ans)if(temp->data =valans trueelse if(temp->data valtemp temp->leftelse temp temp->right deletion of node from binary search tree there is another simple situationsuppose the node we're deleting has only one subtree in the following example' has only subtree to delete node with subtreewe just `link pastthe nodei connect the parent of the node directly to the node' only subtree this always workswhether the one subtree is on the left or on the right deleting ` gives usl lovely professional university
24,045
notes which we normally drawl finallylet us consider the only remaining casehow to delete node having two subtrees for examplehow to delete ` 'we' like to do this with minimum amount of work and disruption to the structure of the tree the standard solution is based on this ideawe leave the node containing ` exactly where it isbut we get rid of the value and find another value to store in the ` node this value is taken from node below the ` ' nodeand it is that node that is actually removed from the tree sohere is the plan starting withl erase but keep its nodel nowwhat value can we move into the vacated node and have binary search treewellhere' how to figure it out if we choose value xthen everything in the left subtree must be smaller than everything in the right subtree must be bigger than let' suppose we're going to get from the left subtree ( is guaranteed because everything in the left subtree is smaller than everything in the right subtree what about ( )if is coming from the left subtree( says that there is unique choice for we must choose to be the largest value in the left subtree in our example is the largest value in the left subtree so if we put in the vacated node and delete it from its current position we will have bst with deleted lovely professional university
24,046
notes here it isl so our general algorithm isto delete nif it has two subtreesreplace the value in with the largest value in its left subtree and then delete the node with the largest value from its left subtree note the largest value in the left subtree will never have two subtrees whybecause if it' the largest value it cannot have right subtree finallythere is nothing special about the left subtree we could do the same thing with the right subtreejust use the smallest value in the right subtree to delete node from binary search tree the method to be used depends on whether node to be deleted has one childtwo childrenor has no child deletion of node with two children if the node to be deleted has two childrenthen the value is replaced by the smallest value in the right sub tree or the largest key value in the left sub treesubsequently the empty node is recursively deleted consider the bst in figure figure binary search tree if the node is to be deleted then first its value is replaced by smallest value in its right subtree by so we will have figure lovely professional university
24,047
notes figure deletion of nod having left and right child now we need todelete this empty node shown in figure thereforethe final structure would be figure figure tree alter deletion of node having left and right child deletion of node with one child consider the binary search tree shown below in figure figure binary tree before deletion of node pointed to by nil lovely professional university
24,048
notes if we want to delete node pointed to by xthen we can do it as followslet be pointer to the node which is the root of the node pointed to by make the left child of the node pointed by to be the right child of the node pointed by xand dispose the node pointed by as shown below in figure figure binary tree after deletion of node pointed to by nil ->lchild ->rchildx->rchild nulldelete( )deletion of node with no child consider the binary search tree shown below in figure figure binary tree before deletion of node pointed to by nil nil let the left child of the node pointed by be niland dispose node pointed by as shown in figure lovely professional university
24,049
figure binary tree after deletion of node pointed to by notes nil nil nil search for key in bst to search the binary tree for particular nodewe use procedures similar to those we used when adding to it beginning at the root nodethe current node and the entered key are compared if the values are equal success is output if the entered value is less than the value in the nodethen it must be in the left-child sub tree if there is no left-child sub treethe value is not in the tree failure is reported if there is left-child subtreethen it is examined the same way similarlyit the entered value is greater than the value in the current nodethe right child is searched figure shows the path through the tree followed in the search for the key figure search for key in bst find-key (key valuenodeif (two values are sameprint value stored in nodereturn (success)else if (key value value stored in current nodeif (left child existsfind-key (key-valueleft hand)lovely professional university
24,050
notes else there is no left subtree return (string not foundelse if (key-value value stored in current nodeif (right child existsfind-key (key-valuerot child)else there is no right subtreereturn (string not foundlab exercise programc program to delete nodewhere the data value of the node to be deleted is knownis as follows#include #include struct tnode int datastruct tnode *lchild*rchild}/ function to get pointer to the node whose data value is given as well as the pointer to its root *struct tnode *getptr(struct tnode *pint keystruct tnode **ystruct tnode *tempifp =nullreturn(null)temp * nullwhiletemp !nullif(temp->data =keyreturn(temp) lovely professional university
24,051
notes else * temp/*store this pointer as root *if(temp->data keytemp temp->lchildelse temp temp->rchildreturn(null)/ function to delete the node whose data value is given *struct tnode *delete(struct tnode * ,int valstruct tnode * * *tempx getptr( ,val,& )ifx =nullprintf("the node does not exists\ ")return( )else /this code is for deleting root node*ifx =ptemp ->lchildy ->rchildp tempwhile(temp->rchild !nulltemp temp->rchildtemp->rchild=yfree( )return( )/this code is for deleting node having both children *ifx->lchild !null & ->rchild !nullif( ->lchild =xlovely professional university
24,052
notes temp ->lchildy->lchild ->lchildwhile(temp->rchild !nulltemp temp->rchildtemp->rchild= ->rchildx->lchild=nullx->rchild=nullelse temp ->rchildy->rchild ->rchildwhile(temp->lchild !nulltemp temp->lchildtemp->lchild= ->lchildx->lchild=nullx->rchild=nullfree( )return( )/this code is for deleting node with on child*if( ->lchild =null & ->rchild !=nullif( ->lchild =xy->lchild ->rchildelse ->rchild ->rchildx->rchildnullfree( )return( )ifx->lchild !null & ->rchild =nullif( ->lchild =xy->lchild ->lchild else ->rchild ->lchildx->lchild nullfree( ) lovely professional university
24,053
notes return( )/this code is for deleting node with no child*if( ->lchild =null & ->rchild =nullif( ->lchild =xy->lchild null else ->rchild nullfree( )return( )/*an iterative function to print the binary tree in inorder*void inorder (struct tnode *pstruct tnode *stack[ ]int toptop - if( !nulltop++stack[toppp ->lchildwhile(top > while !null)/push the left child onto stack*top++stack[top=pp ->lchildp stack[top]top-printf("% \ ", ->data) ->rchildif !null/push right child*top++stack[toppp ->lchildlovely professional university
24,054
notes / function to insert new node in binary search tree to get tree created*struct tnode *insert(struct tnode * ,int valstruct tnode *temp ,*temp if( =nullp (struct tnode *malloc(sizeof(struct tnode))/insert the new node as root node*if( =nullprintf("cannot allocate\ ")exit( ) ->data valp->lchild= ->rchild=nullelse temp /traverse the tree to get pointer to that node whose child will be the newly created node*while(temp !nulltemp temp iftemp ->data valtemp temp ->lchildelse temp temp ->rchildiftemp ->data valtemp ->lchild (struct tnode*)malloc(sizeof(struct tnode));*inserts the newly created node as left child*temp temp ->lchildif(temp =nullprintf("cannot allocate\ ") lovely professional university
24,055
notes exit( )temp ->data valtemp ->lchild=temp ->rchild nullelse temp ->rchild (struct tnode*)malloc(sizeof(struct tnode));*inserts the newly created node as left child*temp temp ->rchildif(temp =nullprintf("cannot allocate\ ")exit( )temp ->data valtemp ->lchild=temp ->rchild nullreturn( )void main(struct tnode *root nullint ,xprintf("enter the number of nodes in the tree\ ")scanf("% ",& )whilen printf("enter the data value\ ")scanf("% ",& )root insert(root, )printf("the created tree is :\ ")inorder (root)printf("\ enter the value of the node to be deleted\ ")scanf("% ",& )root=delete(root, )printf("the tree after deletion is \ ")inorder (root)lovely professional university
24,056
notes explanation this program first creates binary tree with specified number of nodes with their respective data values it then takes the data value of the node to be deletedobtains pointer to the node containing that data valueand obtains another pointer to the root of the node to be deleted depending on whether the node to be deleted is root nodea node with two children node with only one childor node with no childrenit carries out the manipulations as discussed in the section on deleting node after deleting the specified nodeit returns the pointer to the root of the tree input the number of nodes that the tree to be created should have the data values of each node in the tree to be created the data value in the node to be deleted output the data values of the nodes in the tree in inorder before deletion the data values of the nodes in the tree in inorder after deletion question write program to count the number of non-leaf nodes of binary tree application of binary search tree prominent data structure used in many systems programming applications for representing and managing dynamic sets average case complexity of searchinsertand delete operations is (log )where is the number of nodes in the tree one of the applications of binary search tree is the implementation of dynamic dictionary dictionary is an ordered list which is required to be searched frequentlyand is also required to be updated (insertions and deletionsfrequently hence can be very well implemented using binary search treeby making the entries of dictionary into the nodes of binary search tree more efficient implementation of dynamic dictionary involves considering key to be sequence of charactersand instead of searching by comparison of entire keyswe use these characters to determine multi-way branch at each stepthis will allow us to make -way branching according the first letterfollowed by another branch according to the second letter and so on program to create binary search treegiven list of identifiers is given belowchar key[maxlen]struct tnode key nametnode *lchildtnode *rchildvoid btree( lovely professional university
24,057
notes tnode *rootkey itemint nroot nullprintf("number of data values:")scanf("% "& )whilen printf("enter the data value")scanf("% "item)insert(rootitem) - printtree(root)task discuss how will you delete node with one child avl tree an avl tree is another balanced binary search tree it takes its name from the initials of its inventors adelsonvelskii and landis an avl tree has the following propertiesthe sub-trees of every node differ in height by at most one level every sub-tree is an avl tree - - herethe height of the tree is height of one subtree is - while that of another subtree of the same node is - differing from each other by just thereforeit is an avl tree inserting node into avl tree inserting node is somewhat complex and involves number of cases implementations of avl tree insertion rely on adding an extra attribute the balance factor to each node this factor indicates whether the tree is left-heavy (the height of the left sub-tree is greater than the right lovely professional university
24,058
notes sub-tree)balanced (both sub-trees are the same heightor right-heavy (the height of the right sub-tree is greater than the left sub-treeif the balance would be destroyed by an insertiona rotation is performed to correct the balance let us consider the following avl tree in which node has been inserted in the left subtree of node this insertion causes its height to become greater than node- ' right sub-tree right-rotation is performed to correct the imbalanceas shown below avl rotationa tree rotation can be an intimidating concept at first you end up in situation where you're juggling nodesand these nodes have trees attached to themand it can all become confusing very fast find it helps to block out what' going on with any of the subtrees which are attached to the nodes you're fumbling withbut that can be hard left rotation (llimagine we have this situationa lovely professional university
24,059
to fix thiswe must perform left rotationrooted at this is done in the following stepsnotes becomes the new root takes ownership of ' left child as its right childor in this casenull takes ownership of as its left child the tree now looks like thisb / right rotation (rra right rotation is mirror of the left rotation operation described above imagine we have this situationc to fix thiswe will perform single right rotationrooted at this is done in the following stepsb becomes the new root takes ownership of ' right childas its left child in this casethat value is null takes ownership of cas it' right child the resulting treeb / left-right rotation (lror "double leftsometimes single left rotation is not sufficient to balance an unbalanced tree take this situationa perfect it' balanced let' insert 'ba lovely professional university
24,060
notes our initial reaction here is to do single left rotation let' try that our left rotation has completedand we're stuck in the same situation if we were to do single right rotation in this situationwe would be right back where we started what' causing thisthe answer is that this is result of the right subtree having negative balance in other wordsbecause the right subtree was left heavyour rotation was not sufficient what can we dothe answer is to perform right rotation on the right subtree read that again we will perform right rotation on the right subtree we are not rotating on our current root we are rotating on our right child think of our right subtreeisolated from our main treeand perform right rotation on itbeforec afterb after performing rotation on our right subtreewe have prepared our root to be rotated left here is our tree nowa looks like we're ready for left rotation let' do thatb / voila problem solved lovely professional university
24,061
right-left rotiation (rlor "double rightnotes double right rotationor right-left rotationor simply rlis rotation that must be performed when attempting to balance tree which has left subtreethat is right heavy this is mirror operation of what was illustrated in the section on left-right rotationsor double left rotations let' look at an example of situation where we need to perform right-left rotation in this situationwe have tree that is unbalanced the left subtree has height of and the right subtree has height of this makes the balance factor of our root nodecequal to - what do we dosome kind of right rotation is clearly necessarybut single right rotation will not solve our problem let' try ita looks like that didn' work now we have tree that has balance of it would appear that we did not accomplish much that is true what do we dowelllet' go back to the original treebefore we did our pointless right rotationc the reason our right rotation did not workis because the left subtreeor ' 'has positive balance factorand is thus right heavy performing right rotation on tree that has left subtree that is right heavy will result in the problem we just witnessed what do we dothe answer is to make our left subtree left-heavy we do this by performing left rotation our left subtree doing so leaves us with this situationc lovely professional university
24,062
notes this is tree which can now be balanced using single right rotation we can now perform our right rotation rooted at the resultb / balance at last avl operation insertion into avl trees to implement avl treesyou need to maintain the height of each node you insert into an avl tree by performing standard binary tree insertion when you're doneyou check each node on the path from the new node to the root if that node' height hasn' changed because of the insertionthen you are done if the node' height has changedbut it does not violate the balance propertythen you continue checking the next node in the path if the node' height has changed and it now violates the balance propertythen you need to perform one or two rotations to fix the problemand then you are done let' try some examples suppose have the following avl tree - now annotate the nodes with their heightseunice fred binky baby daisy luther daisy calista if insert ahmadtake look at the resulting treeeunice fred binky baby daisy daisy ahmed calista luther the new node ahmad has height of zeroand when travel the path up to the rooti change baby daisy' height to one howeverher node is not imbalancedsince the height of her subtrees are and - moving onbinky' height is unchangedso we can stop the resulting tree is indeed an avl tree lovely professional university
24,063
notes howeversuppose now try to insert waluigi get the following treeeunice fred binky baby daisy calista ahmed luther daisy waluigi traveling from the new node to the rooti see that fred violates the balance condition it' left child has height of - and its right child has height of have to rebalance the tree rebalancing when rebalancei have node whose height is hthat has two children of differing heights one child has height of - and the other has height of - the one whose height is - contains the new node we have to consider two caseswhich 'll name zig-zig and zig-zag you'll see the reasons for the names pretty clearly here is the zig-zig caseh - - - either is the newly added nodeor it is node or - - or - - or - in this casethe path from the imbalanced node (bto the newly added node starts with two right children to rebalance the treeyou perform rotation about node dd - - - - - - or - - or - lovely professional university
24,064
notes node is the new root of the subtree before the insertionnode ' height was - so the height of the subtree has not changed because of the rotation thusinsertion is overand you are left with valid avl tree if the path from the imbalanced node to the newly added node starts with two left childrenthen you have another zig-zig case (the mirror imageyou treat it in the same wayrotate about the imbalanced node' left child before going ontake look at our example above where fred was imbalanced that is zig-zig caseso we can fix it by rotating about luthereunice eunice baby daisy daisy ahmed calista luther binky baby daisy calista ahmed waluigi daisy luther rotate about luther fred binky fred waluigi the other rebalancing case is the zig-zag casepictured belowb - - - - either is the newly added nodeor it is node in or - or - - or - to fix thisyou perform two rotations you rotate about node dand then you rotate about node again this is called double rotation about node here are the two rotationsb - - - - or - - - or - first rotation about lovely professional university
24,065
notes - - - - - or - - or - second rotation about once againthe height of the subtree before deletion was - so when you're done with the double rotationyou are done your tree is balanced againthe mirror image case is treated in the exact same manner here' an example suppose our tree is the followingrather large treeeunice luther binky baby daisy ahmed calista daisy fred dontonio waluigi and suppose we insert boo into the treeeunice luther binky baby daisy ahmed daisy calista boo fred dontonio waluigi checking for balancingwe have to increment every height up to the rootand the root node eunice is imbalanced since the path to the new node starts with left child and right childthis is zig-zag caseand we need to perform double rotation about the grandchild of the imbalanced node -daisy below is the result we have nicely balanced avl treelovely professional university
24,066
notes daisy eunice binky baby daisy ahmed calista dontonio luther boo fred waluigi deletion when you delete nodethere are three things that can happen to the parent its height is decremented by one an example of this is if boo is deleted from the above tree baby daisy' height is decremented by one its height doesn' change and it stays balanced an example of this is if fred is deleted -luther' height is unchanged and it is balanced its height doesn' changebut it becomes imbalanced an example of this is if dontonio is deleted eunice' height is unchangedbut she is imbalanced you handle these three cases in different ways the parent' height is decremented by one when this happensyou check the parent' parentyou keep doing this until you return or you reach the root of the tree the parent' height doesn' change and it stays balanced when this happens you may return deletion is over the parent' height doesn' changebut it becomes imbalanced when this happensyou have to rebalance the subtree rooted at the parent after rebalancingthe subtree' height may be one smaller than it was originally if soyou must continue checking the parent' parent to rebalanceyou need to identify whether you are in zig-zig situation or zig-zag situation and rebalance accordingly how do you do thislook at the following pictureb - - - or - - or - - or - imbalanced identification picture lovely professional university
24,067
the imbalanced node is if the height of subtree is - then the height of will be - and the tree is zig-zig you can rebalance by rotating about node if the height of subtree is - then the height of is - and the tree is zig-zag you rebalance by doing double rotation about the root of if both and have heights of - then you treat it as either zig-zig or zig-zag both work for the purposes of your labtreat this case like zig-zig notes the mirror image works the same way let' look at some examples firstsuppose we delete calista from the following tree binky calista baby daisy ahmed you're left with binky baby daisy ahmed you check calista' old parent binky and although binky' height hasn' changedthe node is imbalanced it' clearly zig-zig treeso you rotate about baby daisy to yield the following tree baby daisy ahmed binky since baby daisy is the rootwe're done let' try more complex example -deleting eunice from the following treedaisy binky baby daisy ahmed calista boo eunice dontonio luther fred lovely professional university
24,068
notes firsteunice has two children sowe find the child with the greatest key in eunice' left subtreewhich is dontoniodelete itand replace eunice with dontonio we start by deleting dontoniodaisy eunice binky baby daisy calista luther ahmed boo fred and we start checking at eunice it is imbalanced looking at itwe see that it' zig-zagso we have to double-rotate about freddaisy binky baby daisy ahmed fred calista eunice luther boo nowthe subtree rooted by fred is balancedbut the subtree' height is one less than it used to beso we need to move to it' parent and check it its height is unchangedand it is balancedso we're done as last stepwe replace eunice with dontonioavl tree algorithms #ifndef avl_tree_h #define avl_tree_h #include "dsexceptions #include /for null using namespace std/avltree class //constructionwith item_not_found object used to signal failed finds //******************public operations******************** /void insertx --insert /void removex --remove (unimplemented/bool containsx --return true if is present /comparable findmin--return smallest item /comparable findmax--return largest item /boolean isempty--return true if emptyelse false /void makeempty--remove all items lovely professional university
24,069
/void printtree--print tree in sorted order notes /******************errors*******************************/throws underflowexception as warranted template class avltree publicavltreerootnull avltreeconst avltree rhs rootnull *this rhs~avltreemakeempty)/*find the smallest item in the tree throw underflowexception if empty *const comparable findminconst ifisemptythrow underflowexception)return findminroot )->element/*find the largest item in the tree throw underflowexception if empty *const comparable findmaxconst ifisemptythrow underflowexception)return findmaxroot )->elementlovely professional university
24,070
notes /*returns true if is found in the tree *bool containsconst comparable xint &comps const return containsxrootcomps)/*test if the tree is logically empty return true if emptyfalse otherwise *bool isemptyconst return root =null/*print the tree contents in sorted order *void printtreeconst ifisemptycout <"empty tree<endlelse printtreeroot )/*make the tree logically empty *void makeemptymakeemptyroot )/*insert into the treeduplicates are ignored * lovely professional university
24,071
notes void insertconst comparable insertxroot )/*remove from the tree nothing is done if is not found *void removeconst comparable cout <"sorryremove unimplemented< <still present<endl/*deep copy *const avltree operator=const avltree rhs ifthis !&rhs makeempty)root clonerhs root )return *thisprivatestruct avlnode comparable elementavlnode *leftavlnode *rightint heightavlnodeconst comparable theelementavlnode *ltavlnode *rtint elementtheelement )leftlt )rightrt )heighth }lovely professional university
24,072
notes avlnode *root/*internal method to insert into subtree is the item to insert is the node that roots the subtree set the new root of the subtree *void insertconst comparable xavlnode ift =null new avlnodexnullnull )else ifx element insertxt->left )ifheightt->left heightt->right = ifx left->element rotatewithleftchildt )else doublewithleftchildt )else ift->element insertxt->right )ifheightt->right heightt->left = ift->right->element rotatewithrightchildt )else doublewithrightchildt )else /duplicatedo nothing ->height maxheightt->left )heightt->right /*internal method to find the smallest item in subtree return node containing the smallest item *avlnode findminavlnode * const lovely professional university
24,073
notes ift =null return nullift->left =null return treturn findmint->left )/*internal method to find the largest item in subtree return node containing the largest item *avlnode findmaxavlnode * const ift !null whilet->right !null ->rightreturn /*internal method to test if an item is in subtree is item to search for is the node that roots the tree *bool containsconst comparable xavlnode *tint &comps const ift =null return falseelse ifx element return containsxt->left++comps)else ift->element return containsxt->right++comps)else return true/match /*****nonrecursive version************************bool containsconst comparable xavlnode * const whilet !null lovely professional university
24,074
notes ifx element ->leftelse ift->element ->rightelse return truereturn false/match /no match *****************************************************/*internal method to make subtree empty *void makeemptyavlnode ift !null makeemptyt->left )makeemptyt->right )delete tt null/*internal method to print subtree rooted at in sorted order *void printtreeavlnode * const ift !null printtreet->left )cout element <endlprinttreet->right )/*internal method to clone subtree lovely professional university
24,075
notes *avlnode cloneavlnode * const ift =null return nullelse return new avlnodet->elementclonet->left )clonet->right ) ->height )/avl manipulations /*return the height of node or - if null *int heightavlnode * const return =null - ->heightint maxint lhsint rhs const return lhs rhs lhs rhs/*rotate binary tree node with left child for avl treesthis is single rotation for case update heightsthen set new root *void rotatewithleftchildavlnode avlnode * ->leftk ->left ->rightk ->right ->height maxheightk ->left )heightk ->right ->height maxheightk ->left ) ->height /*rotate binary tree node with right child for avl treesthis is single rotation for case lovely professional university
24,076
notes update heightsthen set new root *void rotatewithrightchildavlnode avlnode * ->rightk ->right ->leftk ->left ->height maxheightk ->left )heightk ->right ->height maxheightk ->right ) ->height /*double rotate binary tree nodefirst left child with its right childthen node with new left child for avl treesthis is double rotation for case update heightsthen set new root *void doublewithleftchildavlnode rotatewithrightchildk ->left )rotatewithleftchildk )/*double rotate binary tree nodefirst right child with its left childthen node with new right child for avl treesthis is double rotation for case update heightsthen set new root *void doublewithrightchildavlnode rotatewithleftchildk ->right )rotatewithrightchildk )}#endif lovely professional university
24,077
applications of avl trees notes avl trees are applied in the following situations there are few insertion and deletion operations short search time is needed input data is sorted or nearly sorted avl tree structures can be used in situations which require fast searching butthe large cost of rebalancing may limit the usefulness consider the following classic problem in computer science is how to store information dynamically so as to allow for quick look up this searching problem arises often in dictionariestelephone directorysymbol tables for compilers and while storing business records etc the records are stored in balanced binary treebased on the keys (alphabetical or numericalorder the balanced nature of the tree limits its height to (log )where is the number of inserted records avl trees are very fast on searches and replacements buthave moderately high cost for addition and deletion if application does lot more searches and replacements than it does addition and deletionsthe balanced (avlbinary tree is good choice for data structure avl tree also has applications in file systems summary binary trees provide an excellent solution to this problem by making the entries of an ordered list into the nodes of binary treewe shall find that we can search for target key in (log nstepsjust as with binary searchand we shall obtain algorithms for inserting and deleting entries also in time (log nz when we studied binary searchwe drew comparison trees showing the progress of binary search by moving either left (if the target key is smaller than the one in the current node of the treeor right (if the target key is largerz we can regard binary search trees as new abstract data type with its own definition and its own methodsz since binary search trees are special kinds of binary treeswe may consider their methods as special kinds of binary tree methodsz since the entries in binary search trees contain keysand since they are applied for information retrieval in the same way as ordered listswe may study binary search trees as new implementation of the abstract data type ordered list keywords binary search treea binary search tree is binary tree which may be emptyand every node contains an identifier searchingsearching for the key in the given binary search treestart with the root node and compare the key with the data value of the root node lovely professional university
24,078
notes self assessment state whether the following statements are true or false binary search tree is not binary tree which may be fulland every node contains an identifier dictionary is an ordered list which is required to be searched frequentlyand is also required to be updated frequently avl tree invented by adelsonvelskii and landis implementations of avl tree insertion rely on deleting an extra attribute the balance factor to each node identifier of any node in the right sub-tree is greater than the identifier of the root and the left sub-tree as well as right sub-tree both are binary search trees fill in the blanks binary search tree is basically binary treeand therefore it can be traversed is inorderpreorderand to create we use procedure named insert which creates new node with the data value supplied as parameter to itand inserts into an already existing tree whose root pointer is also passed as parameter to from binary search tree the method to be used depends on whether node to be deleted has one childtwo childrenor has no child to search the binary tree for particular nodewe use procedures similar to those we used when to it more efficient implementation of dynamic dictionary involves considering key to be sequence of review questions describe binary search tree also explain how will you create binary search tree how will counting the number of nodes in binary search treeexplain describe deletion of node with one child question - are based on the following binary search tree answer each question independentlyusing the original tree as the basis for each part lovely professional university
24,079
show the keys with which each of the following targets will be compared in search of the preceding binary search tree notes insert each of the following keys into the preceding binary search tree show the comparisons of keys that will be made in each case do each part independentlyinserting the key into the original tree delete each of the following keys from the preceding binary search treeusing the algorithm developed in this section do each part independentlydeleting the key from the original tree draw the binary search trees that function insert will construct for the list of names presented in each of the following orders and inserted into previously empty binary search tree jan guy jon ann jim eva amy tim ron kim tom roy kay dot amy tom tim ann roy dot eva ron kim kay guy jon jan jim jan jon tim ron guy ann jim tom amy eva roy kim dot kay jon roy tom eva tim kim ann ron jan amy dot guy jim kay consider building two binary search trees containing the integer keys to inclusivereceived in the orders all the odd integers in order ( )then then the remaining even integers in order ( then all the odd integers in order ( )then the remaining even integers in order ( which of these trees will be quicker to buildexplain why [try to answer this question without actually drawing the trees prepare package containing the declarations for binary search tree and the functions developed in this section the package should be suitable for inclusion in any application program in each of the followinginsert the keysin the order shownto build them into an avl tree azbycx abcdef mteazgp azbycxdwevf abcdefghijkl avltreisok lovely professional university
24,080
notes answersself assessment false true true false true postorder binary search tree delete node adding characters further readings books brian kernighan and dennis ritchiethe programming languageprentice hall burkhard moniendata structures and efficient algorithmsthomas ottmannspringer krusedata structure program designprentice hall of indianew delhi mark allen welesdata structure algorithm analysis in csecond ed addisonwesley publishing rg dromeyhow to solve it by computercambridge university press shi-kuo changdata structures and algorithmsworld scientific shi-kuo changdata structures and algorithmsworld scientific sorenson and tremblayan introduction to data structure with algorithms thomas cormencharles eleiserson ronald rivestintroduction to algorithmsprentice-hall of india pvt limitednew delhi timothy buddclassic data structures in ++addison wesley online links www en wikipedia org www web-source net www webopedia com lovely professional university
24,081
unit splay trees unit splay trees notes contents objectives introduction splay trees operations splay operation rotations splay tree application summary keywords self assessment review questions further readings objectives after studying this unityou will be able todescribe splay trees explain splay tree operation introduction splay trees are binary search trees that achieve our goals by being self-adjusting in quite remarkable wayevery time we access node of the treewhether for insertion or retrievalwe perform radical surgery on the treelifting the newly accessed node all the way upso that it becomes the root of the modified tree other nodes are pushed out of the way as necessary to make room for this new root nodes that are frequently accessed will frequently be lifted up to become the rootand they will never drift too far from the top position inactive nodeson the other handwill slowly be pushed farther and farther from the root it is possible that splay trees can become highly unbalancedso that single access to node of the tree can be quite expensive later in this sectionhoweverwe shall prove thatover long sequence of accessessplay trees are not at all expensive and are guaranteed to require not many more operations even than avl trees the analytical tool used is called amortized algorithm analysissincelike insurance calculationsthe few expensive cases are averaged in with many less expensive cases to obtain excellent performance over long sequence of operations splay trees splay trees were invented by sleator and tarjan this data structure is essentially binary tree with special update and access rules it has the property to adapt optimally to sequence of tree operations more preciselya sequence of operations on tree with initially nodes takes time ( ln (nm ln ( )lovely professional university
24,082
notes operations splay trees support the following operations we write for setsx for elements and for key values splay(skreturns an access to an element with key in the set in case no such element existswe return an access to the next smaller or larger element split(skreturns (s_ ,s_ )where for each in s_ holdskey[ < and for each in s_ holdsk key[yjoin(s_ ,s_ returns the union s_ s_ conditionfor each in s_ and each in s_ < insert( ,xaugments by delete( ,xremoves from each splitjoindelete and insert operation can be reduced to splay operations and modifications of the tree at the root which take only constant time thusthe run time for each operation is essentially the same as for splay operation splay operation the most important tree operation is splay( )which moves an element to the root of the tree in case is not present in the treethe last element on the search path for is moved instead the run time for splay(xoperation is proportional to the length of the search path for while searching for we traverse the search path top-down let be the last node on that path in second stepwe move along that path by applying rotations as described later the time complexity of maintaining splay tree is analyzed using an amortized analysis consider sequence of operations op_ op_ op_m assume that our data structure has potential one can think of the potential as bank account each tree operation op_i has actual costs proportional to its running time we're paying for the costs c_i of op_i with its amortized costs a_i the difference between concrete and amortized costs is charged against the potential of the data structure this means that we're investing in the potential if the amortized costs are higher that the actual costsotherwise we're decreasing the potential thuswe're paying for the sequence op_ op_ op_m no more than the initial potential plus the sum of the amortized costs a_ a_ a_m the trick of the analysis is to define potential function and to show that each splay operation has amortized costs (ln ( )it follows that the sequence has costs ( ln (nn ln ( ) rotations the splay operation moves the accessed element to the root of the tree this is done using rotations on and parent and grandparent there are two kinds of double rotations and one single rotation due to symmetrywe need mirror-image versions of each rotation type or respectively type or respectively type the last case deals with the situation that the splay node is child of the root thuswe need single rotation or respectively lovely professional university
24,083
splay tree application notes the application is lexicographic search tree (lstfigure an example of lst in lst all the circles and squares are the nodes of the tree each node will contain character and the square nodes are terminal nodes of the strings there are two kinds of edgessolid line edges and dashed line edges in lst solid line edges forms the splay tree and the nodes connected by solid line represent different strings the dashed line edges are used to represent single string therefore the order of the nodes connected by dashed line cannot be changed figure shows an example of lst form the figure it stores different words"at""as""bat""bats""bog""boy""dayand "hewhen string is requested you just splay the character in the string one by one figure shows how to splay character 'ain lst as you can seethe character 'awill not be splayed to the root because 'hand 'dare the prefix of 'abut it will move to the position most near the root in lstafter the string is accessedthe first character of the string will become the root as result the most frequent accessed string will be near the root and lst store the prefix for different strings this reduce the redundancy for storing the strings besides lstthe splay tree can also be used for data compressione dynamic huffman coding lovely professional university
24,084
notes figure splay character 'ain lst splay at 'ad rules for splaying here are the rules for splaying denote the node being accessed as xthe parent of as and the grandparent of as gzigin this casep is the root of the tree zig_leftx if is left child zig_rightx if is right child lovely professional university
24,085
notes figure splay tree zig rotations of node ( )zig_left ( )zig_right zigzagp is not the root of the tree and are opposite types of children (left or rightthe path from to is "crooked zig_right_zag_left if is right child and is left child zig_left_zag_right if is left child and is right child lovely professional university
24,086
notes figure splay tree zig_zag rotations of node ( )zig_right_zag_left ( )zig_left_zag_right zigzigp is not the root of the tree and are the same type of children (left or rightxp and are in straight line zig_zig_left if and are both right children zig_zig_right if and are both left children figure splay tree zig_zig rotations of node (azig_zig_left contd lovely professional university
24,087
notes (bzig_zag_right splay tree algorithms to show that splay trees deliver the promised amortized performancewe define potential function ph(tto keep track of the extra time that can be consumed by later operations on the tree as beforewe define the amortized time taken by single tree operation that changes the tree from to tas the actual time tplus the change in potential ph( ')-ph(tnow consider sequence of operations on treetaking actual times tm and producing trees tm the amortized time taken by the operations is the sum of the actual times for each operation plus the sum of the changes in potentialt tm (ph( ph( )(ph( ph( )(ph(tmph(tm- ) tm ph(tmph( therefore the amortized time for sequence of operations underestimates the actual time by at most the maximum drop in potential ph(tmph( seen over the whole sequence of operations the key to amortized analysis is to define the right potential function given node in binary treelet size(xbe the number of nodes below (including xlet rank(xbe the log base of size(xthen the potential ph(tof tree is the sum of the ranks of all of the nodes in the tree note that if tree has nodes in itthe maximum rank of any node is lg nand therefore the maximum potential of tree is lg this means that over sequence of operations on the treeits potential can decrease by at most lg so the correction factor to amortized time is at most lg nwhich is good nowlet us consider the amortized time of an operation the basic operation of splay trees is splayingit turns out that for tree tany splaying operation on node takes at most amortized time *rank( since the rank of the tree is at most lg( )the splaying operation takes (lg namortized time thereforethe actual time taken by sequence of operations on tree of size is at most (lg nper operation to obtain the amortized time bound for splayingwe consider each of the possible rotation operationswhich take node and move it to new location we consider that the rotation operation itself takes time let (xbe the rank of before the rotationand '(xthe rank of node after the rotation we will show that simple rotation takes amortized time at most ( '(xr( )) and that the other two rotations take amortized time ( '(xr( )there can be only one simple rotation (at the top of the tree)so when the amortized time of all the rotations performed during one splaying is addedall the intermediate terms (xand '(xcancel out and we are left with ( (tr( ) in the worst case where is leaf and has rank this is equal to * ( lovely professional university
24,088
notes simple rotation the only two nodes that change rank are and so the cost is '(xr(xr'(yr(ysince decreases in rankthis is at most '(xr(xsince increases in rankr'(xr(xis positive and this is bounded by ( '(xr( )zig-zig rotation only the nodes xyand change in rank since this is double rotationwe assume it has actual cost and the amortized time is '(xr(xr'(yr(yr'(zr(zsince the new rank of is the same as the old rank of zthis is equal to (xr'(yr(yr'(zthe new rank of is greater than the new rank of yand the old rank of is less than the old rank yso this is at most (xr'(xr(xr'( '( (xr'(znowlet (xbe the old size of and let '(xbe the new size of consider the term '(xr(xr'(zthis must be at least because it is equal to lg( '( )/ ( )lg( '( )/ '( )notice that this is the sum of two ratios where '(xis on top nowbecause '( > (xs'( )the way to make the sum of the two logarithms as small as possible is to choose (xs(zs'( )/ but in this case the sum of the logs is therefore the term '(xr(xr'(zmust be at least substituting it for the red abovewe see that the amortized time is at most ( '(xr(xr'( ) '( (xr'( ( '(xr( )as required zig-zag rotation againthe amortized time is '(xr(xr'(yr(yr'(zr(zbecause the new rank of is the same as the old rank of zand the old rank of is less than the old rank of ythis is (xr'(yr(yr'( < (xr'(yr'(znow consider the term '(xr'(yr'(zby the same argument as beforethis must be at least so we can replace the constant above while maintaining bound on amortized time<( '(xr'(yr'( ) (xr'(yr'( ( '(xr( )therefore amortized run time in this case too is bounded by ( '(xr( ))and this completes the proof of the amortized complexity of splay tree operations summary splay trees are self-adjusting binary search trees in which every access for insertion or retrieval of nodelifts that node all the way up to become the rootpushing the other nodes out of the way to make room for this new root of the modified tree hencethe frequently accessed nodes will frequently be lifted up and remain around the root positionwhile the most infrequently accessed nodes would move farther and farther away from the root lovely professional university
24,089
keywords notes access timethe time required to access and retrieve word from high-speed memory is few microseconds at most splay treessplay trees are binary search trees which are self adjusting self assessment choose the appropriate answer splay trees were invented by (asleator (btarjan (cnewton (dboth (aand (bthe run time for each operation is essentially the same as for (asplay operation (bzero operation (cplay operation (dnone of the above state whether the following statements are true or false the time complexity of maintaining splay tree is analyzed using an amortized analysis each node does not contain character fill in the blanks the of maintaining splay tree is analyzed using an amortized analysis the trick of the analysis is to define potential function and to show that each splay operation has the key to is to define the right potential function there are two kinds of rotations and one single rotation review questions explain splay operation in splay trees "the time complexity of maintaining splay tree is analyzed using an amortized analysis explain " splay tree does not keep track of heights and does not use any balance factors like an avl treeexplain lovely professional university
24,090
notes consider the following binary search treesplay this tree at each of the following keys in turnd each part builds on the previousthat isuse the final tree of each solution as the starting tree for the next part "splay trees are binary search trees that achieve our goals by being self-adjusting in quite remarkable waydiscuss "it is possible that splay trees can become highly unbalancedso that single access to node of the tree can be quite expensiveexplain answersself assessment ( ( true true time complexity amortized costs (ln ( ) amortized analysis double further readings books brian kernighan and dennis ritchiethe programming languageprentice hall burkhard moniendata structures and efficient algorithmsthomas ottmannspringer krusedata structure program designprentice hall of indianew delhi mark allen welesdata structure algorithm analysis in csecond ed addisonwesley publishing rg dromeyhow to solve it by computercambridge university press shi-kuo changdata structures and algorithmsworld scientific shi-kuo changdata structures and algorithmsworld scientific sorenson and tremblayan introduction to data structure with algorithms lovely professional university
24,091
thomas cormencharles eleiserson ronald rivestintroduction to algorithmsprentice-hall of india pvt limitednew delhi notes timothy buddclassic data structures in ++addison wesley online links www en wikipedia org www web-source net www webopedia com lovely professional university
24,092
mandeep kaurlovely professional university unit -trees notes contents objectives introduction -trees structure of -trees height of -trees operations on -trees inserting new item -tree-deleting an item -tree algorithms applications summary keywords self assessment review questions further readings objectives after studying this unityou will be able toexplain the concept of -trees describe -trees algorithms introduction the key factors which have been discussed in this unit about the -trees in data structures while dealing with many problems in computer scienceengineering and many other disciplinesit is needed to impose hierarchical structure on collection of data items for examplewe need to impose hierarchical structure on collection of data items while preparing organizational charts and genealogiesto represent the syntactic structure of source programs in compilers -tree is tree data structure that keeps data sorted and allows insertions and deletions that is logarithmically proportional to file size it is commonly used in databases and file systems -trees in -treesinternal nodes can have variable number of child nodes within some pre-defined range when data is inserted or removed from nodeits number of child nodes changes in order to maintain the pre-defined rangeinternal nodes may be joined or split because range of child nodes is permittedb-trees do not need re-balancing as frequently as other self balancing lovely professional university
24,093
search treesbut may waste some spacesince nodes are not entirely full the lower and upper bounds on the number of child nodes are typically fixed for particular implementation notes -tree is kept balanced by requiring that all leaf nodes are at the same depth this depth will increase slowly as elements are added to the treebut an increase in the overall depth is infrequentand results in all leaf nodes being one more hop further removed from the root figure schema showing the -tree structure -trees are balanced trees that are optimized for situations when part or the entire tree must be maintained in secondary storage such as magnetic disk since disk accesses are expensive (time consumingoperationsa -tree tries to minimize the number of disk accesses examplea -tree with height of and branching factor of can store over one billion keys but requires at most two disk accesses to search for any node structure of -trees unlike binary-treeeach node of -tree may have variable number of keys and children the keys are stored in non-decreasing order each key has an associated child that is the root of subtree containing all nodes with keys less than or equal to the key but greater than the preceding key node also has an additional rightmost child that is the root for subtree containing all keys greater than any keys in the node -tree has minimum number of allowable children for each node known as the minimization factor if is this minimization factorevery node must have at least keys under certain circumstancesthe root node is allowed to violate this property by having fewer than keys every node may have at most keys orequivalently children since each node tends to have large branching factor ( large number of children)it is typically necessary to traverse relatively few nodes before locating the desired key if access to each node requires disk accessthen -tree will minimize the number of disk accesses required the minimization factor is usually chosen so that the total size of each node corresponds to multiple of the block size of the underlying storage device this choice simplifies and optimizes disk access consequentlya -tree is an ideal data structure for situations where all data cannot reside in primary storage and accesses to secondary storage are comparatively expensive (or time consuminglovely professional university
24,094
notes height of -trees for greater than or equal to onethe height of an -key -tree of height with minimum degree greater than or equal to <log + the worst case height is (log nsince the "branchinessof -tree can be large compared to many other balanced tree structuresthe base of the logarithm tends to be largethereforethe number of nodes visited during search tends to be smaller than required by other tree structures although this does not affect the asymptotic worst case heightb-trees tend to have smaller heights than other trees with the same asymptotic height operations on -trees the algorithms for the searchcreateand insert operations are shown below note that these algorithms are single passin other wordsthey do not traverse back up the tree since -trees strive to minimize disk accesses and the nodes are usually stored on diskthis single-pass approach will reduce the number of node visits and thus the number of disk accesses simpler double-pass approaches that move back up the tree to fix violations are possible since all nodes are assumed to be stored in secondary storage (diskrather than primary storage (memory)all references to given node be be preceeded by read operation denoted by diskread similarlyonce node is modified and it is no longer neededit must be written out to secondary storage with write operation denoted by disk-write the algorithms below assume that all nodes referenced in parameters have already had corresponding disk-read operation new nodes are created and assigned storage with the allocate-node call the implementation details of the disk-readdisk-writeand allocate-node functions are operating system and implementation dependent -tree-search(xki < while keyi[xdo < if < [xand keyi[xthen return (xiif leaf[xthen return nil else disk-read(ci[ ]return -tree-search(ci[ ]kthe search operation on -tree is analogous to search on binary tree instead of choosing between left and right child as in binary treea -tree search must make an -way choice the correct child is chosen by performing linear search of the values in the node after finding the value greater than or equal to the desired valuethe child pointer to the immediate left of that value is followed if all values are less than the desired valuethe rightmost child pointer is followed of coursethe search can be terminated as soon as the desired node is found since the running time of the search operation depends upon the height of the treeb-tree-search is (logt nb-tree-create(tx <allocate-node( lovely professional university
24,095
notes leaf[ <true [ < disk-write(xroot[ < the -tree-create operation creates an empty -tree by allocating new root node that has no keys and is leaf node only the root node is permitted to have these propertiesall other nodes must meet the criteria outlined previously the -tree-create operation runs in time ( -tree-split-child(xiyz <allocate-node(leaf[ <leaf[yn[ < for < to do keyj[ <keyj+ [yif not leaf[ythen for < to do cj[ <cj+ [yn[ < for < [ downto do cj+ [ <cj[xci+ < for < [xdownto do keyj+ [ <keyj[xkeyi[ <keyt[yn[ < [ disk-write(ydisk-write(zdisk-write(xif is node becomes "too full,it is necessary to perform split operation the split operation moves the median key of node into its parent where is the ith child of new nodezis allocatedand all keys in right of the median key are moved to the keys left of the median key remain in the original node the new nodezbecomes the child immediately to the right of the median key that was moved to the parent yand the original nodexbecomes the child immediately to the left of the median key that was moved into the parent the split operation transforms full node with keys into two nodes with keys each note one key is moved into the parent node the -tree-split-child algorithm will run in time (twhere is constant -tree-insert(tkr <root[tif [ lovely professional university
24,096
notes then <allocate-node(root[ < leaf[ <false [ < < -tree-split-child( rb-tree-insert-nonfull(skelse -tree-insert-nonfull(rkb-tree-insert-nonfull(xki < [xif leaf[xthen while > and keyi[xdo keyi+ [ <keyi[xi < keyi+ [ < [ < [ disk-write(xelse while >and keyi[xdo < < disk-read(ci[ ]if [ci[ ] then -tree-split-child(xici[ ]if keyi[xthen < -tree-insert-nonfull(ci[ ]kto perform an insertion on -treethe appropriate node for the key must be located using an algorithm similiar to -tree-search nextthe key must be inserted into the node if the node is not full prior to the insertionno special action is requiredhoweverif the node is fullthe node must be split to make room for the new key since splitting the node results in moving one key to the parent nodethe parent node must not be full or another split operation is required this process may repeat all the way up to the root and may require splitting the root node this approach requires two passes the first pass locates the node where the key should be insertedthe second pass performs any required splits on the ancestor nodes since each access to node may correspond to costly disk accessit is desirable to avoid the second pass by ensuring that the parent node is never full to accomplish thisthe presented algorithm splits any full nodes encountered while descending the tree although this approach may result in unecessary split operationsit guarantees that the parent never needs to be split and eliminates the need for second pass up the tree task in twenty words or lessexplain how treesort works lovely professional university
24,097
inserting new item notes when inserting an itemfirst do search for it in the -tree if the item is not already in the -treethis unsuccessful search will end at leaf if there is room in this leafjust insert the new item here note that this may require that some existing keys be moved one to the right to make room for the new item if instead this leaf node is full so that there is no room to add the new itemthen the node must be "splitwith about half of the keys going into new node to the right of this one the median (middlekey is moved up into the parent node (of courseif that node has no roomthen it may have to be split as well note that when adding to an internal nodenot only might we have to move some keys one position to the rightbut the associated pointers have to be moved right as well if the root node is ever splitthe median key moves up into new root nodethus causing the tree to increase in height by one insert the following letters into what is originally an empty -tree of order order means that node can have maximum of children and keys all nodes other than the root must have minimum of keys the first letters get inserted into the same noderesulting in this picturea when we try to insert the hwe find no room in this nodeso we split it into nodesmoving the median item up into new root node note that in practice we just leave the and in the current node and place the and into new node to the right of the old one inserting ekand proceeds without requiring any splitsg inserting requires split note that happens to be the median key and so is moved up into the parent node lovely professional university
24,098
notes the letters fwland are then added without needing any split when is addedthe rightmost leaf must be split the median item is moved up into the parent node note that by moving up the median keythe tree is kept fairly balancedwith keys in each of the resulting nodes the insertion of causes the leftmost leaf to be split happens to be the median key and so is the one moved up into the parent node the letters prxand are then added without any need of splittingfinallywhen is addedthe node with npqand splitssending the median up to the parent howeverthe parent node is fullso it splitssending the median up to form new root node note how the pointers from the old parent node stay in the revised node that contains and lovely professional university
24,099
notes -tree-deleting an item deletion of key from -tree is possiblehoweverspecial care must be taken to ensure that the properties of -tree are maintained several cases must be considered if the deletion reduces the number of keys in node below the minimum degree of the treethis violation must be corrected by combining several nodes and possibly reducing the height of the tree if the key has childrenthe children must be rearranged in the -tree as we left it at the end of the last sectiondelete of coursewe first do lookup to find since is in leaf and the leaf has more than the minimum number of keysthis is easy we move the over where the had been and the over where the had been this givesnextdelete the since is not in leafwe find its successor (the next item in ascending order)which happens to be wand move up to replace the that waywhat we really have to do is to delete from the leafwhich we already know how to dosince this leaf has extra keys in all cases we reduce deletion to deletion in leafby using this method lovely professional university