id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
24,500 | data structures using descendant node descendant node is any successor node on any path from the node to leaf node leaf nodes do not have any descendants in the tree given in fig nodes cgjand are the descendants of node root node level number every node in the tree is assigned level number in such way that the root node is at level children of the root node are at level number thusevery node is at one level higher than its parent soall child nodes have level number given by parent' level number degree degree of node is equal to the number of children that node has the degree of leaf node is zero figure tree in-degree in-degree of node is the number of edges arriving at that node out-degree out-degree of node is the number of edges leaving that node types of trees trees are of following types general trees forests binary trees binary search trees expression trees tournament trees general trees general trees are data structures that store elements hierarchically the top node of tree is the root node and each nodeexcept the roothas parent node in general tree (except the leaf nodesmay have zero or more sub-trees general trees which have sub-trees per node are called ternary trees howeverthe number of sub-trees for any node may be variable for examplea node can have sub-treewhereas some other node can have sub-trees although general trees can be represented as adtsthere is always problem when another sub-tree is added to node that already has the maximum number of sub-trees attached to it even the algorithms for searchingtraversingaddingand deleting nodes become much more complex as there are not just two possibilities for any node but multiple possibilities to overcome the complexities of general treeit may be represented as graph data structure (to be discussed later)thereby losing many of the advantages of the tree processes thereforea better option is to convert general trees into binary trees general tree when converted to binary tree may not end up being well formed or fullbut the advantages of such conversion enable the programmer to use the algorithms for processes that are used for binary trees with minor modifications forests forest is disjoint union of trees set of disjoint trees (or forestsis obtained by deleting the root and the edges connecting the root node to nodes at level we have already seen that every node of tree is the root of some sub-tree thereforeall the sub-trees immediately below node form forest |
24,501 | (af (bh figure forest and its corresponding tree forest can also be defined as an ordered set of zero or more general trees while general tree must have roota forest on the other hand may be empty because by definition it is setand sets can be empty we can convert forest into tree by adding single node as the root node of the tree for examplefig (ashows forest and fig (bshows the corresponding tree similarlywe can convert general tree into forest by deleting the root node of the tree binary trees binary tree is data structure that is defined as collection of elements called nodes in binary treethe topmost element is called the root nodeand each node has or at the most children node that has zero children is called leaf node or terminal node every node contains data elementa left pointer which points to the left childand right pointer which points to the right child the root element is pointed by 'rootpointer if root nullthen it means the tree is empty figure shows binary tree in the figurer is the root node and the two trees and are called the left and right sub-trees of is said to be the left successor of likewiset is called the right successor of note that the left sub-tree of the root node consists of the nodes and similarlythe right sub-tree of the root node consists of nodes and in the treeroot node has two successors and node has two successor nodes and node has two successors and node has no successor node has two successor nodes and node has two successors and finallynode has only one successor binary tree is recursive by definition as every node in the tree contains left sub-tree and right sub-tree even the terminal nodes contain an empty left sub-tree and an empty right sub-tree look at fig nodes and have no successors and thus said to have empty sub-trees root node figure binary tree root node (level (level (level (level figure levels in binary tree terminology parent if is any node in that has left successor and right successor then is called the parent of and correspondinglys and are called the left child and the right child of every node other than the root node has parent level number every node in the binary tree is assigned level number (refer fig the root node is defined to be at level the left and the right child of the root node have level number similarlyevery node is at one level higher than its parents so all child nodes are defined to have level number as parent' level number degree of node it is equal to the number of children that node has the degree of leaf node is zero for examplein the treedegree of node is degree of node is zero and degree of node is sibling all nodes that are at the same level and share the same parent are called siblings (brothersfor examplenodes and nodes and nodes and nodes and and nodes and are siblings |
24,502 | data structures using tree tree tca similar binary trees two binary trees and tcare said to be similar if both these trees have the same structure figure shows two similar binary trees copies two binary trees and tcare said to be copies if they have similar structure and if they have same content at the corresponding nodes figure shows that tcis copy of figure similar binary trees tree tree tca figure edge it is the line connecting node to any of its successors binary tree of nodes has exactly edges because every node except the root node is connected to its parent via an edge path sequence of consecutive edges for examplein fig the path from the root node to the node is given as and leaf node node that has no children is called leaf node or terminal node the leaf nodes in the tree are and tcis copy of depth the depth of node is given as the length of the path from the root to the node the depth of the root node is zero height of tree it is the total number of nodes on the path from the root node to the deepest node in the tree tree with only root node has height of binary tree of height has at least nodes and at most nodes this is because every level will have at least one node and can have at most nodes soif every level has two nodes then tree with height will have at the most nodes as at level there is only one element called the root the height of binary tree with nodes is at least log ( + and at most in-degree/out-degree of node it is the number of edges arriving at node the root node is the only node that has an in-degree equal to zero similarlyout-degree of node is the number of edges leaving that node binary trees are commonly used to implement binary search treesexpression treestournament treesand binary heaps complete binary trees complete binary tree is binary tree that satisfies two properties firstin complete binary treeevery levelexcept possibly the lastis completely filled secondall nodes appear as far left as possible in complete binary tree tnthere are exactly nodes and level of can have at most nodes figure shows complete binary tree note that in fig level has nodelevel has nodeslevel has nodeslevel has nodes which is less than the maximum of nodes in fig tree has exactly nodes they have been purposely labelled from to so that it is easy for the reader to find the parent nodethe right child nodeand the left child node of the given node the formula can be given as--if is parent nodethen its left child can be calculated as and its right child can be calculated as for examplethe children of the node are ( and ( similarlythe parent of the node can be calculated as / given the node its parent can be calculated as / the height of tree tn having exactly nodes is given as figure complete binary tree hn log ( |
24,503 | this meansif tree has , , nodesthen its height is extended binary trees binary tree is said to be an extended binary tree (or -treeif each node in the tree has either no child or exactly two children figure shows how an ordinary binary tree is converted into an extended binary tree in an extended binary treenodes having two children are called ( (binternal nodes and nodes having no children are called external figure (abinary tree and (bextended nodes in fig the internal nodes are represented using circles binary tree and the external nodes are represented using squares to convert binary tree into an extended treeevery empty sub-tree is replaced by new node the original nodes in the tree are the internal nodesand the new nodes added are called the external nodes representation of binary trees in the memory in the computer' memorya binary tree can be maintained either by using linked representation or by using sequential representation linked representation of binary trees in the linked representation of binary treeevery node will have three partsthe data elementa pointer to the left nodeand pointer to the right node so in cthe binary tree is built with node type given below struct node struct node *leftint datastruct node *right}every binary tree has pointer rootwhich points to the root element (topmost elementof the tree if root nullthen the tree is empty consider the binary tree given in fig the schematic diagram of the linked representation of the binary tree is shown in fig in fig the left position is used to point to the left child of the node or to store the address of the left child of the node the middle position is used to store the data finallythe right position is used to point to the right child of the node or to store the address of the right child of the node empty sub-trees are represented using (meaning null figure linked representation of binary tree look at the tree given in fig note how this tree is represented in the main memory using linked list (fig |
24,504 | data structures using root avail figure binary tree left data right - - - - - - - - - - - - - figure linked representation of binary tree example given the memory representation of tree that stores the names of family membersconstruct the corresponding tree from the given data solution root avail amar raj janak pallav rudraksh sanjay deepak ridhiman tanush kuvam kunsh left names pallav right - amar deepak janak - - - kuvam rudraksh raj - - - kunsh - - tanush - - ridhiman - sanjay |
24,505 | figure sequential representation of binary trees sequential representation of trees is done using single or one-dimensional arrays though it is the simplest technique for memory representationit is inefficient as it requires lot of memory space sequential binary tree follows the following rules one-dimensional arraycalled treeis used to store the elements of tree the root of the tree will be stored in the first location that istree[ will store the data of the root element the children of node stored in location will be stored in locations ( kand ( + the maximum size of the array tree is given as ( - )where is the height of the tree an empty tree or sub-tree is specified using null if tree[ nullthen the tree is empty figure shows binary tree and its corresponding sequential representation the tree has nodes and its height is binary tree and its sequential representation binary search trees binary search treealso known as an ordered binary treeis variant of binary tree in which the nodes are arranged in an order we will discuss the concept of binary search trees and different operations performed on them in the next expression trees binary trees are widely used to store algebraic expressions for exampleconsider the algebraic expression given asa figure expression tree exp ( ( dthis expression can be represented using binary tree as shown in fig example given an expressionexp (( ( )(( ^ ( ))construct the corresponding binary tree solution expression tree example given the binary treewrite down the expression that it represents solution |
24,506 | data structures using expression for the above binary tree is [{( / ( * ){( )/( )} example given the expressionexp econstruct the corresponding binary tree solution use the operator precedence chart to find the sequence in which operations will be performed the given expression can be written as exp (( (( /cd)eb creating binary tree from general tree tournament trees we all know that in tournamentsay of chessn number of players participate to expression tree declare the winner among all these playersa couple of matches are played and usually three rounds are played in the game in every match of round number of matches are played in which two players play the game against each other the number of matches that will be played in round will depend on the number of players for exampleif there are players participating in chess tournamentthen matches will be played in round every match of round will be played between two players then in round the winners of round will play against each other similarlyin round the winners of round will play against each other and the person who wins round is declared the winner tournament trees are used to represent this concept in tournament tree (also called selection tree)each external node represents player and each internal node represents the winner of the match played between the players represented by its children nodes these tournament trees are also called winner trees because they are being used to record the winner at each level we can also have loser tree that records the loser at each level consider the tournament tree given in fig there are players in total whose names are represented using abcdefgand in round and bc and de and fand finally and play against each other in round the winners of round that isadeand play against each other in round the winners of round and figure tournament tree play against each other whosoever wins is declared the winner in the treethe root node specifies the winner the rules for converting general tree to binary tree are given below note that general tree is converted into binary tree and not binary search tree rule root of the binary tree root of the general tree rule left child of node leftmost child of the node in the binary tree in the general tree rule right child of node in the binary tree right sibling of the node in the general tree example convert the given general tree into binary tree |
24,507 | now let us build the binary tree step node is the root of the general treeso it will also be the root of the binary tree step left child of node is the leftmost child of node in the general tree and right step child of node is the right sibling of the node in the general tree since node has no right sibling in the general treeit has no right child in the binary tree step now process node left child of is and its right child is (right sibling in general treestep step now process node left child of is (leftmost childand its right child is (right sibling in general treeb step now process node left child of is (leftmost childthere will be no right child of because it has no right sibling in the general tree step now process node there will be no left child of in the binary tree because has no left child in the general tree howeveri has right sibling jso it will be added step as the right child of step now process node left child of is (leftmost childthere will be no right child of because it has no right sibling in the general tree step step step step step step now process all the unprocessed nodes (efghkin the same fashionso the resultant binary tree can be given as follows traversing binary tree traversing binary tree is the process of visiting each node in the tree exactly once in systematic way unlike linear data structures in which the elements are traversed sequentiallytree is nonlinear data structure in which the elements can be traversed in many different ways there are different algorithms for tree traversals these algorithms differ in the order in which the nodes are visited in this sectionwe will discuss these algorithms pre-order traversal to traverse non-empty binary tree in pre-orderthe following operations are performed recursively at each node the algorithm works bya visiting the root nodeb traversing the left sub-treeand finally traversing the right sub-tree figure binary tree |
24,508 | consider the tree given in fig the pre-order traversal of the tree is given as abc root node firstthe left sub-tree nextand then the right sub-tree pre-order traversal is also called as depth-first traversal in this algorithmthe left sub-tree is always traversed before the right sub-tree the word 'prein the pre-order specifies that the root node is accessed prior to any other nodes in step repeat steps to while tree !null the left and right sub-trees pre-order algorithm step write tree -data is also known as the nlr traversal algorithm step preorder(tree -leftstep preorder(tree -right(node-left-rightthe algorithm for pre-order [end of looptraversal is shown in fig step end pre-order traversal algorithms are used to extract prefix notation from an expression tree for exampleconsider the expressions given below when we traverse the elements of tree using the pre-order traversal algorithmthe expression that we get is prefix expression figure algorithm for pre-order traversal (from fig (from fig of example (from fig of example traversal orderabdghlecfijand traversal orderabdcdefghand (ah (bexample in figs (aand ( )find the sequence of nodes that will be visited using pre-order traversal algorithm solution in-order traversal to traverse non-empty binary tree in in-orderthe following operations are performed recursively at each node the algorithm works by traversing the left sub-tree visiting the root nodeand finally traversing the right sub-tree consider the tree given in fig the in-order traversal of the tree is given as baand left sub-tree firstthe root node nextand then the right sub-tree in-order traversal is also called as symmetric traversal in this algorithmthe left sub-tree is always traversed before the root node and the right sub-tree the word 'inin the in-order specifies that the root node is accessed in between the left and the right sub-trees in-order algorithm is also known as the lnr traversal algorithm (left-node-rightthe algorithm for in-order traversal is shown in fig step repeat steps to while tree !null step inorder(tree -leftstep write tree -data step inorder(tree -right[end of loopstep end figure algorithm for in-order traversal in-order traversal algorithm is usually used to display the elements of binary search tree hereall the elements with value lower than given value are accessed before the elements with higher value we will discuss binary search trees in detail in the next |
24,509 | example for the trees given in example find the sequence of nodes that will be visited using in-order traversal algorithm traversal ordergdhlbeacifkand traversal orderbdaehgifand post-order traversal to traverse non-empty binary tree in post-orderthe following operations are performed recursively at each node the algorithm works by traversing the left sub-tree traversing the right sub-treeand finally visiting the root node consider the tree given in fig the post-order traversal of the tree is given as bcstep repeat steps to while tree !null and left sub-tree firstthe right sub-tree nextstep postorder(tree -leftand finally the root node in this algorithmthe step postorder(tree -rightleft sub-tree is always traversed before the right step write tree -data [end of loopsub-tree and the root node the word 'postin step end the post-order specifies that the root node is accessed after the left and the right sub-trees figure algorithm for post-order traversal post-order algorithm is also known as the lrn traversal algorithm (left-right-nodethe algorithm for post-order traversal is shown in fig post-order traversals are used to extract postfix notation from an expression tree example for the trees given in example give the sequence of nodes that will be visited using post-order traversal algorithm traversal orderglhdebikjfcand traversal orderdbhigfecand level-order traversal in level-order traversalall the nodes at level are accessed before going to the next level this algorithm is also called as the breadth-first traversal algorithm consider the trees given in fig and note the level order of these trees ( (btraversal orderaband traversal orderabcdefghijland figure binary trees (ctraversal orderabcdefghand |
24,510 | data structures using constructing binary tree from traversal results we can construct binary tree if we are given at least two traversal results the first traversal must be the in-order traversal and the second can be either pre-order or post-order traversal the in-order traversal result will be used to determine the left and the right child nodesand the pre-order/post-order can be used to determine the root node for exampleconsider the traversal results given belowin-order traversald pre-order traversala herewe have the in-order traversal sequence and pre-order traversal sequence follow the steps given below to construct the treestep use the pre-order sequence to determine the root node of the tree the first element would be the root node step elements on the left side of the root node in the in-order traversal sequence form the left sub-tree of the root node similarlyelements on the right side of the root node in the in-order traversal sequence form the right sub-tree of the root node step recursively select each element from pre-order traversal sequence and create its left and right sub-trees from the in-order traversal sequence look at fig which constructs the tree from its traversal results now consider the in-order traversal dbe fcg fcg and post-order traversal sequences of given binary tree before constructing the binary treeremember that in post-order traversal the root node is the last node rest of the steps will be the same as mentioned figure above fig in-order traversald dbhe fjcg post order traversald dbhe if dbhe hei figure steps to show binary tree huffman' tree huffman coding is an entropy encoding algorithm developed by david huffman that is widely used as lossless data compression technique the huffman coding algorithm uses variablelength code table to encode source character where the variable-length code table is derived on the basis of the estimated probability of occurrence of the source character the key idea behind huffman algorithm is that it encodes the most common characters using shorter strings of bits than those used for less common source characters the algorithm works by creating binary tree of nodes that are stored in an array node can be either leaf node or an internal node initiallyall the nodes in the tree are at the leaf level and store the source character and its frequency of occurrence (also known as weightwhile the internal node is used to store the weight and contains links to its child nodesthe external node contains the actual character conventionallya ' represents following the left |
24,511 | figure child and ' represents following the right child finished tree that has leaf nodes will have internal nodes the running time of the algorithm depends on the length of the paths in the tree sobefore going into further details of huffman codinglet us first learn how to calculate the length of the paths in the tree the external path length of binary tree is defined as the sum of all path lengths summed over each path from the root to an external node the internal path length is also defined in the same manner the internal path length of binary tree is defined as the sum of all path lengths summed over each path from the root to an internal node look at the binary tree given in fig binary tree the internal path lengthli the external path lengthle note thatli le thusli lewhere is the number of internal nodes now if the tree has external nodes and each external node is assigned weightthen the weighted path length is defined as the sum of the weighted path lengths thereforep wnln where wi and li are the weight and path length of an external node ni example consider the trees and given belowcalculate their weighted external path lengths binary tree solution weighted external path length of can be given asp * * * * * * weighted external path length of can be given asp * * * * * weighted external path length of can be given asp * * * * technique given nodes and their weightsthe huffman algorithm is used to find tree with minimumweighted path length the process essentially begins by creating new node whose children are the two nodes with the smallest weightsuch that the new node' weight is equal to the sum of the children' weight that isthe two nodes are merged into one node this process is repeated |
24,512 | data structures using until the tree has only one node such tree with only one node is known as the huffman tree the huffman algorithm can be implemented using priority queue in which all the nodes are placed in such way that the node with the lowest weight is given the highest priority the algorithm is shown in fig step create leaf node for each character add the character and its weight or frequency of occurrence to the priority queue step repeat steps to while the total number of nodes in the queue is greater than step remove two nodes that have the lowest weight (or highest prioritystep create new internal node by merging these two nodes as children and with weight equal to the sum of the two nodesweights step add the newly created node to the queue figure huffman algorithm example create huffman tree with the following nodes arranged in priority queue |
24,513 | |
24,514 | data structures using table range of characters that can be coded using code character table range of characters that can be coded using data coding when we want to code our data (characterusing bitsthen we use bits to code characters for exampleif = then two characters can be coded if these two characters are and bthen can be coded as and can be coded as and vice versa look at tables and which show the range of characters that can be coded by using = and = nowif we have to code the data string abbbbbbaaaacdefgggghthen the corresponding code would be this coding scheme has fixed-length code because every character is being coded using the same number of bits although this technique of coding is simplecoding the data can be made more efficient by using variable-length code you might have observed that when we write text in englishall the characters are not used frequently for examplecharacters like aeiand are used more frequently than wxyz and so on sothe basic idea is to assign shorter code to the frequently occurring characters and longer to less frequently occurring characters variable-length coding is preferred over fixed-length coding because it requires lesser number of bits to encode the same data for variable-length encodingwe first build huffman tree firstarrange all the characters in priority queue in which the character with the lowest frequency of occurrence has the highest priority thencreate huffman tree as explained in the previous section figure shows huffman tree that is used for encoding the data set in the huffman treecircles contain the cumulative weights of their child nodes every left branch is coded with and every right branch is coded with sothe characters aerwxyand are coded as shown in table code character table characters with their codes character code figure huffman tree thuswe see that frequent characters have shorter code and infrequent characters have longer code applications of trees trees are used to store simple as well as complex data here simple means an integer valuecharacter value and complex data means structure or record |
24,515 | trees are often used for implementing other types of data structures like hash tablessetsand maps self-balancing treered-black tree is used in kernel schedulingto preempt massively multiprocessor computer operating system use (we will study red-black trees in next another variation of treeb-trees are prominently used to store tree structures on disc they are used to index large number of records (we will study -trees in -trees are also used for secondary indexes in databaseswhere the index facilitates select operation to answer some range criteria trees are an important data structure used for compiler construction trees are also used in database design trees are used in file system directories trees are also widely used for information storage and retrieval in symbol tables points to remember tree is data structure which is mainly used to store hierarchical data tree is recursively defined as collection of one or more nodes where one node is designated as the root of the tree and the remaining nodes can be partitioned into non-empty sets each of which is sub-tree of the root in binary treeevery node has zerooneor at the most two successors node that has no successors is called leaf node or terminal node every node other than the root node has parent the degree of node is equal to the number of children that node has the degree of leaf node is zero all nodes that are at the same level and share the same parent are called siblings two binary trees having similar structure are said to be copies if they have the same content at the corresponding nodes binary tree of nodes has exactly edges the depth of node is given as the length of the path from the root to the node the depth of the root node is zero binary tree of height has at least nodes and at most nodes the height of binary tree with nodes is at least log ( + and at most in-degree of node is the number of edges arriving at that node the root node is the only node that has an in-degree equal to zero similarlyout-degree of node is the number of edges leaving that node in complete binary treeevery level (except possibly the lastis completely filled and nodes appear as far left as possibly binary tree is said to be an extended binary tree (or -treeif each node in the tree has either no children or exactly two children pre-order traversal is also called as depth-first traversal it is also known as the nlr traversal algorithm (nodeleft-rightand is used to extract prefix notation from an expression tree in-order algorithm is known as the lnr traversal algorithm (left-node-rightsimilarlypost-order algorithm is known as the lrn traversal algorithm (left-right-nodethe huffman coding algorithm uses variablelength code table to encode source character where the variable-length code table is derived on the basis of the estimated probability of occurrence of the source character exercises review questions explain the concept of tree discuss its applications what are the two ways of representing binary trees in the memorywhich one do you prefer and why list all possible non-similar binary trees having four nodes draw the binary expression tree that represents the following postfix expressionab+ * |
24,516 | data structures using write short notes on(acomplete binary trees (bextended binary trees (ctournament trees (dexpression trees (ehuffman trees (fgeneral trees (gforests consider the tree given below nowdo the following(aname the leaf nodes (bname the non-leaf nodes (cname the ancestors of (dname the descendants of (ename the siblings of (ffind the height of the tree (gfind the height of sub-tree rooted at (hfind the level of node (ifind the in-orderpre-orderpost-orderand levelorder traversal for the expression tree given belowdo the following(aextract the infix expression it represents (bfind the corresponding prefix and postfix expressions (cevaluate the infix expressiongiven avail left - - data right - - - - - - - - - - - draw the memory representation of the binary tree given below convert the prefix expression -/ab*+bcd into infix expression and then draw the corresponding expression tree consider the trees given below and state whether they are complete binary tree or full binary tree what is the maximum number of levels that binary search tree with nodes can have what is the maximum height of tree with nodes what is the maximum number of nodes that can be found in binary tree at levels and draw all possible non-similar binary trees having three nodes draw the binary tree having the following memory representationroot |
24,517 | consider the trees and given below and calculate their weighted path lengths pre-order traversal is also called (adepth first (bbreadth first (clevel order (din-order the huffman algorithm can be implemented using (adequeue (bqueue (cpriority queue (dnone of these total number of nodes at the nth level of binary tree can be given as ( ( + ( ( - true or false consider the trees and given below and find the huffman coding for the characters nodes that branch into child nodes are called parent nodes the size of tree is equal to the total number of nodes leaf node does not branch out further node that has no successors is called the root node binary tree of nodes has exactly edges every node has parent the huffman coding algorithm uses variablelength code table the internal path length of binary tree is defined as the sum of all path lengths summed over each path from the root to an external node fill in the blanks multiple-choice questions degree of leaf node is ( ( ( ( the depth of root node is ( ( ( ( binary tree of height has at least nodes and at most nodes ( ( + ( ( parent node is also known as the node size of tree is basically the number of in the tree the maximum number of nodes at the kth level of binary tree is in binary treeevery node can have maximum of successors nodes at the same level that share the same parent are called two binary trees are said to be copies if they have similar and the height of binary tree with nodes is at least and at most binary tree is said to be an extended binary tree if traversal algorithm is used to extract prefix notation from an expression tree in huffman treethe code of character depends on |
24,518 | efficient binary trees learning objective in this we will discuss efficient binary trees such as binary search treesavl treesthreaded binary treesred-black treesand splay trees this is an extension of binary trees binary search trees we have already discussed binary trees in the previous binary search treealso known as an ordered binary treeis variant of binary trees in which the nodes are arranged in an order in binary search treeall the nodes in the left sub-tree have value less than that of the root node correspondinglyall the nodes in the right sub-tree have value either equal to or greater than the root node the same rule is applicable to every sub-tree in the tree (note that binary search tree may or may not contain duplicate valuesdepending on its implementation look at fig the root node is the left sub-tree of the root node consists of nodes and all these nodes have smaller values than the root node the right sub-tree of the root node consists of nodes and recursivelyeach of the sub-trees also obeys the binary search tree constraint for examplein the left sub-tree of the root node is the root and all elements in its left sub-tree ( are smaller than while all nodes in its right sub-tree ( and are greater than the root node' value since the nodes in binary search tree are orderedthe time needed to search an element in the tree is greatly reduced whenever we search for an elementwe do not figure binary search tree |
24,519 | need to traverse the entire tree at every nodewe get hint regarding which sub-tree to search in for examplein the given treeif we have to search for then we know that we have to scan only the left sub-tree if the value is present in the treeit will only be in the left sub-treeas is smaller than (the root node' valuethe left sub-tree has root node with the value since is greater than we will move to the right sub-treewhere we will find the element thusthe average running time of search operation is (log )as at every stepwe eliminate half of the sub-tree from the search process due to its efficiency in searching elementsbinary search trees are widely used in dictionary problems where the code always inserts and searches the elements that are indexed by some key value binary search trees also speed up the insertion and deletion operations the tree has speed advantage when the data in the structure changes rapidly binary search trees are considered to be efficient data structures especially when compared with sorted linear arrays and linked lists in sorted arraysearching can be done in (log ntimebut insertions and deletions are quite expensive in contrastinserting and deleting elements in linked list is easierbut searching for an element is done in (ntime howeverin the worst casea binary search tree will take (ntime to search for an element the worst case would occur when the tree is linear chain of nodes as given in fig to summarizea binary search tree is binary tree with the following propertiesthe left sub-tree of node contains values that are less than ' value ( (athe right sub-tree of node contains values that are greater figure (aleft skewedand (bthan ' value right skewed binary both the left and the right binary trees also satisfy these search trees properties andthusare binary search trees example solution state whether the binary trees in fig are binary search trees or not (no (yes (no figure binary trees example create binary search tree using the following data elements solution (step (step (step (step (step (step (step (step |
24,520 | data structures using (step (step (step (step figure binary search tree (step (step (step operations on binary search trees in this sectionwe will discuss the different operations that are performed on binary search tree all these operations require comparisons to be made between the nodes searching for node in binary search tree figure searching node with value in the given binary search tree the search function is used to find whether given value is present in the tree or not the searching process begins at the (step (step root node the function first checks if the binary search tree is empty if it is emptythen the value we are searching for is not present in the tree sothe search algorithm terminates by displaying an appropriate message howeverif there are nodes in the treethen the search function checks to see if the key value of the current node is equal to the value to be searched if notit checks if the value to be searched for is less than the value of the current nodein which case it should be recursively called on (step (step the left child node in case the value is greater than the value of the current nodeit should be recursively called on the right child node look at fig the figure shows how binary tree is searched to find specific element firstsee how the tree will be traversed to find the node with value the procedure to find the node with value is illustrated in fig the procedure to find the node with value is shown in fig the search would terminate after reaching figure searching node with value in the given binary search tree node as it does not have any right child |
24,521 | (step (step now let us look at the algorithm to search for an element in the binary search tree as shown in fig in step we check if the value stored at the current node of tree is equal to val or if the current node is nullthen we return the current node of tree otherwiseif the value stored at the current node is less than valthen the algorithm is recursively called on its right sub-treeelse the algorithm is called on its left sub-tree inserting new node in binary search tree the insert function is used to add new node with given figure searching node with the value value at the correct position in the binary search tree in the given binary search tree adding the node at the correct position means that the new node should not violate the properties of the binary search tree figure shows the algorithm to insert given value in binary search tree the initial code for the insert function is similar to the search function this is because we first find the correct position where the insertion has to be done and then add the node at that position the insertion function changes the structure of the tree thereforewhen the insert function is called recursivelythe function should return the new tree pointer in step of the algorithmthe insert function checks if the current node of tree is null if it is searchelement (treevalnullthe algorithm simply adds the nodeelse it looks at the current node' value and then step if tree -data val or tree null recurs down the left or right sub-tree return tree else if the current node' value is less than that if val data of the new nodethen the right sub-tree is return searchelement(tree -leftvaltraversedelse the left sub-tree is traversed else the insert function continues moving down return searchelement(tree -rightvalthe levels of binary tree until it reaches [end of if[end of ifleaf node the new node is added by following step end the rules of the binary search trees that isif the new node' value is greater than that figure algorithm to search for given value in binary of the parent nodethe new node is inserted search tree in the right sub-treeelse it is inserted in the left sub-tree the insert function requires time insert (treevalproportional to the height of the tree in the worst case it takes (log ntime to execute step if tree null allocate memory for tree in the average case and (ntime in the worst set tree -data val case set tree -left tree -right null look at fig which shows insertion of else values in given tree we will take up the case if val data of inserting and insert(tree -leftval else insert(tree -rightval[end of if[end of ifstep end figure algorithm to insert given value in binary search tree deleting node from binary search tree the delete function deletes node from the binary search tree howeverutmost care should be taken that the properties of the binary search tree are not violated and nodes are not |
24,522 | data structures using (step (step (step lost in the process we will take up three cases in this section and discuss how node is deleted from binary search tree (step (step (step (step case deleting node that has no children look at the binary search tree given in fig if we have to delete node we can simply remove this node without any issue this is the simplest case of deletion figure inserting nodes with values and in the given binary search tree (step (step (step (step case deleting node with one child to handle this casethe node' child is set as the child of the node' parent in other wordsreplace the node with its child nowif the node is the left child of its parentthe node' child becomes the left child of the node' parent correspondinglyif the node is the right child of its parentthe node' child becomes the right child of the node' parent look at the binary search tree shown in fig and see how deletion of node is handled case deleting node with two children to handle this casereplace the node' value figure deleting node from the given binary search tree with its in-order predecessor (largest value in the left sub-treeor in-order successor (step (step (step (step (smallest value in the right sub-treethe in-order predecessor or the successor can then be deleted using any of the above cases look at the binary search tree given in fig and see how deletion of node with value is handled replace with this deletion could also be handled by replacing node with its in-order successoras shown in fig figure deleting node from the given binary search tree nowlet us look at fig which (step (step (step (step shows the algorithm to delete node from binary search tree in step of the algorithmwe first check if tree=nullbecause if it is truethen the node to be deleted is not present in the tree howeverif that is not the casethen we check if the value to be deleted is less than replace node with delete leaf node the current node' data in case the value is lesswe call the algorithm recursively on the figure deleting node from the given binary search tree node' left sub-treeotherwise the algorithm delete node |
24,523 | (step (step (step (step (step figure replace node with replace node delete leaf node with deleting node from the given binary search tree delete (treevalstep if tree null write "val not found in the treeelse if val data delete(tree->leftvalelse if val tree -data delete(tree -rightvalelse if tree -left and tree -right set temp findlargestnode(tree -leftset tree -data temp -data delete(tree -lefttemp -dataelse set temp tree if tree -left null and tree -right null set tree null else if tree -left !null set tree tree -left else set tree tree -right [end of iffree temp [end of ifstep end is called recursively on the node' right sub-tree note that if we have found the node whose value is equal to valthen we check which case of deletion it is if the node to be deleted has both left and right childrenthen we find the in-order predecessor of the node by calling findlargestnode(tree -leftand replace the current node' value with that of its in-order predecessor thenwe call delete(tree -lefttemp -datato delete the initial node of the in-order predecessor thuswe reduce the case of deletion into either case or case of deletion if the node to be deleted does not have any childthen we simply set the node to null last but not the leastif the node to be deleted has either left or right child but not boththen the current node is replaced by its child node and the initial child node is deleted from the tree the delete function requires time proportional to the height of the tree in the worst case it takes (log ntime to execute in the average case and (ntime in the worst case determining the height of binary search tree in order to determine the height of binary search treewe calculate the height of figure algorithm to delete node from binary search tree the left sub-tree and the right sub-tree whichever height is greater is added to it for exampleif the height of the left sub-tree is greater than that of the right sub-treethen is added to the left sub-treeelse is added to the right sub-tree look at fig since the height of the right sub-tree is greater than the height of the left sub-treethe height of the tree height (right sub-tree figure shows recursive algorithm that determines the height of binary search tree in step of the algorithmwe first check if the current node of the tree null if the condition is truethen is returned to the calling code otherwisefor every node we recursively call the algorithm to calculate the height of its left sub-tree as well as its right sub-tree the height of the tree at that node is given by adding to the height of the left sub-tree or the height of right sub-treewhichever is greater figure binary search tree with height determining the number of nodes determining the number of nodes in binary search tree is similar to determining its height to calculate the total number of elements/nodes |
24,524 | data structures using in the treewe count the number of nodes in the left sub-tree and the right sub-tree height (treestep if tree null return else set leftheight height(tree -leftset rightheight height(tree -rightif leftheight rightheight return leftheight else return rightheight [end of if[end of ifstep end number of nodes totalnodes(left sub-treetotalnodes(right sub-tree consider the tree given in fig the total number of nodes in the tree can be calculated astotal nodes of left sub-tree total nodes of left sub-tree total nodes of tree ( total nodes of tree figure shows recursive algorithm to calculate the number of nodes in binary search tree for every nodewe recursively call the figure algorithm to determine the height of binary algorithm on its left sub-tree as well as the right search tree sub-tree the total number of nodes at given node is then returned by adding to the number of nodes in its left as well as right sub-tree however if the tree is empty that is tree nullthen the number of nodes will be zero figure binary search tree determining the number of internal nodes to calculate the total number of internal nodes or non-leaf nodeswe count the number of internal nodes in the left sub-tree and the right sub-tree and add to it ( is added for the root nodetotalnodes(treestep if tree null return else return totalnodes(tree -lefttotalnodes(tree -right [end of ifstep end figure algorithm to calculate the number of nodes in binary search tree totalinternalnodes(treestep if tree null return [end of ifif tree -left null and tree -right null return else return totalinternalnodes(tree -lefttotalinternalnodes(tree -right [end of ifstep end figure algorithm to calculate the total number of internal nodes in binary search tree number of internal nodes totalinternalnodes(left sub-treetotalinternalnodes(right sub-tree consider the tree given in fig the total number of internal nodes in the tree can be calculated astotal internal nodes of left sub-tree total internal nodes of right sub-tree total internal nodes of tree ( total internal nodes of tr figure shows recursive algorithm to calculate the total number of internal nodes in binary search tree for every nodewe recursively call the algorithm on its left subtree as well as the right sub-tree the total number of internal nodes at given node is then returned by adding internal nodes in its left as well as right sub-tree howeverif the tree is emptythat is tree nullthen the number of internal nodes will be zero also if there is only one node in the treethen the number of internal nodes will be zero determining the number of external nodes to calculate the total number of external nodes or leaf nodeswe add the number of |
24,525 | external nodes in the left sub-tree and the right sub-tree however if the tree is emptythat is tree nullthen the number of external nodes will be zero but if there is only one node in the treethen the number of external nodes will be one number of external nodes totalexternalnodes(left sub-treetotalexternalnodes (right sub-treeconsider the tree given in fig the total number of external nodes in the given tree can be calculated astotal external nodes of left sub-tree total external nodes of left sub-tree total external nodes of tree totalexternalnodes(treestep if tree null return else if tree -left null and tree -right null return else return totalexternalnodes(tree -lefttotalexternalnodes(tree -right[end of ifstep end figure algorithm to calculate the total number of external nodes in binary search tree tc figure binary search tree and its finding the mirror image of binary search tree mirror image of binary search tree is obtained by interchanging the left sub-tree with the right sub-tree at every node of the tree for examplegiven tree tthe mirror image of can be obtained as tcconsider the tree given in fig figure shows recursive algorithm to obtain the mirror image of binary search tree in the algorithmif tree !nullthat is if the current node in the tree has one or more nodesthen the algorithm is recursively called at every node in the tree to swap the nodes in its left and right sub-trees mirrorimage(treestep if tree !null mirrorimage(tree -leftmirrorimage(tree -rightset temp tree -left set tree -left tree -right set tree -right temp [end of ifstep end figure figure shows recursive algorithm to calculate the total number of external nodes in binary search tree for every nodewe recursively call the algorithm on its left sub-tree as well as the right sub-tree the total number of external nodes at given node is then returned by adding the external nodes in its left as well as right sub-tree however if the tree is emptythat is tree nullthen the number of external nodes will be zero also if there is only one node in the treethen there will be only one external node (that is the root nodealgorithm to obtain the mirror image mirror image tcof binary search tree deleting binary search tree to delete/remove an entire binary search tree from the memorywe first delete the elements/nodes in the left sub-tree and then delete the nodes in the right sub-tree the algorithm shown in fig gives recursive procedure to remove the binary search tree finding the smallest node in binary search tree the very basic property of the binary search tree states that the smaller value will occur in the left sub-tree if |
24,526 | data structures using the left sub-tree is nullthen the value of the root node will be smallest as compared to the nodes in the right sub-tree soto find the node with the smallest valuewe find the value of the leftmost node of the left sub-tree the recursive algorithm to find the smallest node in binary search tree is shown in fig deletetree(treefindsmallestelement(treestep if tree !null deletetree (tree -leftdeletetree (tree -rightfree (tree[end of ifstep end step if tree null or tree -left null returen tree else return findsmallestelement(tree -left[end of ifstep end figure alogrithm to delete binary figure algorithm to find the smallest node in binary search tree search tree finding the largest node in binary search tree to find the node with the largest valuewe find the value of the rightmost node of the right subtree howeverif the right sub-tree is emptythen the root node will be the largest value in the tree the recursive algorithm to find the largest node in binary search tree is shown in fig findlargestelement(treestep if tree null or tree -right null return tree else return findlargestelement(tree -right[end of ifstep end figure algorithm to find the largest node in binary search tree smallest node (left-most child of the left sub-tree figure largest node (right-most child of the right sub-treebinary search tree consider the tree given in fig the smallest and the largest node can be given asprogramming example write program to create binary search tree and perform all the operations discussed in the preceding sections #include #include #include struct node int datastruct node *leftstruct node *right}struct node *treevoid create_tree(struct node *)struct node *insertelement(struct node *int)void preordertraversal(struct node *)void inordertraversal(struct node *) |
24,527 | void postordertraversal(struct node *)struct node *findsmallestelement(struct node *)struct node *findlargestelement(struct node *)struct node *deleteelement(struct node *int)struct node *mirrorimage(struct node *)int totalnodes(struct node *)int totalexternalnodes(struct node *)int totalinternalnodes(struct node *)int height(struct node *)struct node *deletetree(struct node *)int main(int optionvalstruct node *ptrcreate_tree(tree)clrscr()do printf("\ ******main menu******\ ")printf("\ insert element")printf("\ preorder traversal")printf("\ inorder traversal")printf("\ postorder traversal")printf("\ find the smallest element")printf("\ find the largest element")printf("\ delete an element")printf("\ count the total number of nodes")printf("\ count the total number of external nodes")printf("\ count the total number of internal nodes")printf("\ determine the height of the tree")printf("\ find the mirror image of the tree")printf("\ delete the tree")printf("\ exit")printf("\ \ enter your option ")scanf("% "&option)switch(optioncase printf("\ enter the value of the new node ")scanf("% "&val)tree insertelement(treeval)breakcase printf("\ the elements of the tree are \ ")preordertraversal(tree)breakcase printf("\ the elements of the tree are \ ")inordertraversal(tree)breakcase printf("\ the elements of the tree are \ ")postordertraversal(tree)breakcase ptr findsmallestelement(tree)printf("\ smallest element is :% ",ptr->data)breakcase ptr findlargestelement(tree)printf("\ largest element is % "ptr->data)breakcase printf("\ enter the element to be deleted ")scanf("% "&val) |
24,528 | data structures using tree deleteelement(treeval)breakcase printf("\ total no of nodes % "totalnodes(tree))breakcase printf("\ total no of external nodes % "totalexternalnodes(tree))breakcase printf("\ total no of internal nodes % "totalinternalnodes(tree))breakcase printf("\ the height of the tree % ",height(tree))breakcase tree mirrorimage(tree)breakcase tree deletetree(tree)break}while(option!= )getch()return void create_tree(struct node *treetree nullstruct node *insertelement(struct node *treeint valstruct node *ptr*nodeptr*parentptrptr (struct node*)malloc(sizeof(struct node))ptr->data valptr->left nullptr->right nullif(tree==nulltree=ptrtree->left=nulltree->right=nullelse parentptr=nullnodeptr=treewhile(nodeptr!=nullparentptr=nodeptrif(valdatanodeptr=nodeptr->leftelse nodeptr nodeptr->rightif(valdataparentptr->left ptrelse parentptr->right ptrreturn treevoid preordertraversal(struct node *tree |
24,529 | if(tree !nullprintf("% \ "tree->data)preordertraversal(tree->left)preordertraversal(tree->right)void inordertraversal(struct node *treeif(tree !nullinordertraversal(tree->left)printf("% \ "tree->data)inordertraversal(tree->right)void postordertraversal(struct node *treeif(tree !nullpostordertraversal(tree->left)postordertraversal(tree->right)printf("% \ "tree->data)struct node *findsmallestelement(struct node *treeif(tree =null|(tree->left =null)return treeelse return findsmallestelement(tree ->left)struct node *findlargestelement(struct node *treeif(tree =null|(tree->right =null)return treeelse return findlargestelement(tree->right)struct node *deleteelement(struct node *treeint valstruct node *cur*parent*suc*psuc*ptrif(tree->left==nullprintf("\ the tree is empty ")return(tree)parent treecur tree->leftwhile(cur!=null &val!cur->dataparent curcur (valdata)cur->left:cur->rightif(cur =nullprintf("\ the value to be deleted is not present in the tree")return(tree)if(cur->left =nullptr cur->rightelse if(cur->right =null |
24,530 | data structures using ptr cur->leftelse /find the in-order successor and its parent psuc curcur cur->leftwhile(suc->left!=nullpsuc sucsuc suc->leftif(cur==psuc/situation suc->left cur->rightelse /situation suc->left cur->leftpsuc->left suc->rightsuc->right cur->rightptr suc/attach ptr to the parent node if(parent->left =curparent->left=ptrelse parent->right=ptrfree(cur)return treeint totalnodes(struct node *treeif(tree==nullreturn else return(totalnodes(tree->lefttotalnodes(tree->right )int totalexternalnodes(struct node *treeif(tree==nullreturn else if((tree->left==null&(tree->right==null)return else return (totalexternalnodes(tree->lefttotalexternalnodes(tree->right))int totalinternalnodes(struct node *treeif(tree==null|((tree->left==null&(tree->right==null))return else return (totalinternalnodes(tree->lefttotalinternalnodes(tree->right )int height(struct node *treeint leftheightrightheight |
24,531 | if(tree==nullreturn else leftheight height(tree->left)rightheight height(tree->right)if(leftheight rightheightreturn (leftheight )else return (rightheight )struct node *mirrorimage(struct node *treestruct node *ptrif(tree!=nullmirrorimage(tree->left)mirrorimage(tree->right)ptr=tree->leftptr->left ptr->righttree->right ptrstruct node *deletetree(struct node *treeif(tree!=nulldeletetree(tree->left)deletetree(tree->right)free(tree)output *******main menu****** insert element preorder traversal inorder traversal postorder traversal find the smallest element find the largest element delete an element count the total number of nodes count the total number of external nodes count the total number of internal nodes determine the height of the tree find the mirror image of the tree delete the tree exit enter your option enter the value of the new node enter the value of the new node enter the value of the new node enter your option enter your option threaded binary trees threaded binary tree is the same as that of binary tree but with difference in storing the null pointers consider the linked representation of binary tree as given in fig |
24,532 | data structures using in the linked representationa number of nodes contain null pointereither in their left or right fields or in both this space that is wasted in storing null pointer can be efficiently used to store some other useful piece of information for examplethe null entries can be replaced to store pointer to the in-order predecessor or the in-order figure linked representation of binary tree successor of the node these special pointers are called threads and binary trees containing threads are called threaded trees in the linked representation of threaded binary treethreads will be denoted using arrows there are many ways of threading binary tree and each type may vary according to the way the tree is traversed in this book we will discuss in-order traversal of the tree apart from thisa threaded binary tree may figure (abinary tree without threading correspond to one-way threading or two way threading in one-way threadinga thread will appear either in the right field or the left field of the node one-way threaded tree is also called single-threaded tree if the thread appears in the left fieldthen the left field will be made to point to the in-order predecessor of the node such one-way threaded tree is called figure (blinked representation of the binary tree left-threaded binary tree on the contrary(without threadingif the thread appears in the right fieldthen it will point to the in-order successor of the node such one-way threaded tree is called rightthreaded binary tree in two-way threaded treealso called double-threaded treethreads will appear in both the left and the right field of the node while the left field will point to the in-order predecessor of the nodethe right field will point to its successor two-way threaded binary tree is also called fully threaded binary tree one-way threading and two-way threading of binary trees are explained below figure shows binary tree without threading and its corresponding linked representation the in-order traversal of the tree is given as figure (alinked representation of the binary tree with one-way threading one-way threading figure shows binary tree with oneway threading and its corresponding linked representation node contains null pointer in its right fieldso it will be replaced to point to node which is its in-order successor similarlythe right field of node will point to node the right field of node will point to node the right field of node will point to node |
24,533 | the right field of node will point to node and the right field of node will contain null because it has no in-order successor two-way threading figure shows binary tree with two-way threading and its corresponding linked representation node contains null pointer in its left fieldso it will be replaced to point to node which is its in-order predecessor similarlythe left field of node will contain null because it has no in-order predecessorfigure (bbinary tree with one-way threading the left field of node will point to node the left field of node will point to node the left field of node will point to node the left field of node will contain and the left field of node will point to node figure (alinked representation of the binary tree with threading(bbinary tree with two-way threading nowlet us look at the memory representation of binary tree without threadingwith one-way threadingand with two-way threading this is illustrated in fig left data right avail root - - - - - - - - - - - - - ( figure avail root left data right - - - - - - - - ( avail root left data right - - (cmemory representation of binary trees(awithout threading(bwith one-wayand (ctwo-way threading |
24,534 | data structures using traversing threaded binary tree for every nodevisit the left sub-tree firstprovided if one exists and has not been visited earlier then the node (rootitself is followed by visiting its right sub-tree (if one existsin case there is no right sub-treecheck for the threaded link and make the threaded node the current node in consideration the algorithm for in-order traversal of threaded binary tree is given in fig step check if the current node has left child that has not been visited if left child exists that has not been visitedgo to step else go to step step add the left child in the list of visited nodes make it as the current node and then go to step step if the current node has right childgo to step else go to step step make that right child as current node and go to step step print the node and if there is threaded node make it the current node step if all the nodes have visited then end else go to step figure algorithm for in-order traversal of threaded binary tree let' consider the threaded binary tree given in fig and traverse it using the algorithm node has left child which has not been visited soadd in the list of visited nodesmake it as the current node node has left child which has not been visited soadd in the list of visited nodesmake it as the current node figure threaded node does not have any left or right childso print and check for binary tree its threaded link it has threaded link to node so make node the current node node has left child which has already been visited howeverit does not have right child nowprint and follow its threaded link to node make node the current node node has left child that has been already visited so print node has right child which has not yet been visitedso make it the current node node has left child (node which has not been visitedso make it the current node node does not have any left or right child so print howeverit does have threaded link which points to node make node the current node node has left child which has already been visited so print now there are no nodes leftso we end here the sequence of nodes printed is-- advantages of threaded binary tree it enables linear traversal of elements in the tree linear traversal eliminates the use of stacks which in turn consume lot of memory space and computer time it enables to find the parent of given element without explicit use of parent pointers since nodes contain pointers to in-order predecessor and successorthe threaded tree enables forward and backward traversal of the nodes as given by in-order fashion thuswe see the basic difference between binary tree and threaded binary tree is that in binary trees node stores null pointer if it has no child and so there is no way to traverse back |
24,535 | programming example write program to implement simple right in-threaded binary trees #include #include struct tree int valstruct tree *rightstruct tree *leftint thread}struct tree *root nullstruct treeinsert_node(struct tree *rootstruct tree *ptrstruct tree *rtif(root =nullroot ptrif(rt !nullroot->right rtroot->thread else if(ptr->val valroot->left insert_node(root->leftptrroot)else if(root->thread = root->right insert_node(nullptrrt)root->thread= else root->right insert_node(root->rightptrrt)return rootstruct treecreate_threaded_tree(struct tree *ptrint numprintf("\ enter the elementspress - to terminate ")scanf("% "&num)while(num !- ptr (struct tree*)malloc(sizeof(struct tree))ptr->val numptr->left ptr->right nullptr->thread root insert_node(rootptrnull)printf(\ enter the next element ")fflush(stdin)scanf("% "&num)return rootvoid inorder(struct tree *rootstruct tree *ptr root*prevdo while(ptr !nullprev ptrptr ptr->left |
24,536 | data structures using if(prev !nullprintf(% "prev->val)ptr prev->rightwhile(prev !null &prev->threadprintf(% "ptr->val)prev ptrptr ptr->right}while(ptr !null)void main(/struct tree *root=nullclrscr()create_threaded_tree()printf(\ the in-order traversal of the tree can be given as ")inorder(root)getch()output enter the elementspress - to terminate enter the next element enter the next element enter the next element enter the next element enter the next element - the in-order traversal of the tree can be given as avl trees avl tree is self-balancing binary search tree invented by adelson-velsky and landis in the tree is named avl in honour of its inventors in an avl treethe heights of the two sub-trees of node may differ by at most one due to this propertythe avl tree is also known as height-balanced tree the key advantage of using an avl tree is that it takes (log ntime to perform searchinsertand delete operations in an average case as well as the worst case because the height of the tree is limited to (log nthe structure of an avl tree is the same as that of binary search tree but with little difference in its structureit stores an additional variable called the balancefactor thusevery node has balance factor associated with it the balance factor of node is calculated by subtracting the height of its right sub-tree from the height of its left sub-tree binary search tree in which every node has balance factor of - or is said to be height balanced node with any other balance factor is considered to be unbalanced and requires rebalancing of the tree balance factor height (left sub-treeheight (right sub-treeif the balance factor of node is then it means that the left sub-tree of the tree is one level higher than that of the right sub-tree such tree is therefore called as left-heavy tree if the balance factor of node is then it means that the height of the left sub-tree (longest path in the left sub-treeis equal to the height of the right sub-tree if the balance factor of node is - then it means that the left sub-tree of the tree is one level lower than that of the right sub-tree such tree is therefore called as right-heavy tree look at fig note that the nodes and have no childrenso their balance factor node has one left child and zero right child sothe height of left sub-tree whereas the height of right sub-tree thusits balance factor look at node it has left |
24,537 | sub-tree with height whereas the height of right sub-tree thusits balance factor similarlythe balance factor of node = and node has balance factor of ( nowlook at figs (aand (bwhich show right-heavy avl tree and balanced avl tree - - ( ( (cfigure (aleft-heavy avl tree(bright-heavy tree(cbalanced tree the trees given in fig are typical candidates of avl trees because the balancing factor of every node is either or - howeverinsertions and deletions from an avl tree may disturb the balance factor of the nodes andthusrebalancing of the tree may have to be done the tree is rebalanced by performing rotation at the critical node there are four types of rotationsll rotationrr rotationlr rotationand rl rotation the type of rotation that has to be done will vary depending on the particular situation in the following sectionwe will discuss insertiondeletionsearchingand rotations in avl trees operations on avl trees searching for node in an avl tree searching in an avl tree is performed exactly the same way as it is performed in binary search tree due to the height-balancing of the treethe search operation takes (log ntime to complete since the operation does not modify the structure of the treeno special provisions are required inserting new node in an avl tree insertion in an avl tree is also done in the same way as it is done in binary search tree in the avl treethe new node is always inserted as the leaf node but the step of insertion is usually followed by an additional step of rotation rotation is done to restore the balance of the tree howeverif insertion of the new node does not disturb the balance factorthat isif the balance factor of every node is still - or then rotations are not required during insertionthe new node is inserted as the leaf nodeso it will always have balance factor equal to zero the only nodes whose balance factors will change are those which lie in the path between the root of the tree and the newly inserted node the possible changes which may take place in any node on the path are as followsinitiallythe node was either leftor right-heavy and after insertionit becomes balanced initiallythe node was balanced and after insertionit becomes either leftor right-heavy initiallythe node was heavy (either left or rightand the new node has been inserted in the heavy sub-treethereby creating an unbalanced sub-tree such node is said to be critical node consider the avl tree given in fig if we insert new node with the value then the new tree will still be balanced and no rotations will be required in this case look at the tree given in fig which shows the tree after inserting node |
24,538 | data structures using - - - - - - figure avl tree figure avl tree after inserting node with the value figure avl tree let us take another example to see how insertion can disturb the balance factors of the nodes and how rotations are done to restore the avl property of tree look at the tree given in fig after inserting new node with the value the new tree - will be as shown in fig note that there are three nodes in the tree that have their balance factors - and - thereby - disturbing the avlness of the tree sohere comes the need to perform rotation to perform rotationour first task is to find the critical node critical node is the nearest ancestor node on the path from the inserted node to the root whose balance factor is neither - - nor in the tree given abovethe critical node is the second task in rebalancing the tree is to determine which type of rotation has to be done there are four types of rebalancing figure avl tree after inserting rotations and application of these rotations depends on the position node with the value of the inserted node with reference to the critical node the four categories of rotations arell rotation the new node is inserted in the left sub-tree of the left sub-tree of the critical node rr rotation the new node is inserted in the right sub-tree of the right sub-tree of the critical node lr rotation the new node is inserted in the right sub-tree of the left sub-tree of the critical node rl rotation the new node is inserted in the left sub-tree of the right sub-tree of the critical node ll rotation let us study each of these rotations in detail firstwe will see where and how ll rotation is applied consider the tree given in fig ( ( ( + which shows an avl tree tree (ais an avl tree in tree ( ) new ( ( ( ( ( (hnode is inserted in the left sub-tree of the left height + sub-tree of the critical node (node is the new node critical node because it is the closest ancestor ( ( (cwhose balance factor is not - or )so figure ll rotation in an avl tree we apply ll rotation as shown in tree (cnote the new node has now become part of tree |
24,539 | while rotationnode becomes the rootwith and as its left and right child and become the left and right sub-trees of example consider the avl tree given in fig and insert into it solution - (step (step figure avl tree rr rotation let us now discuss where and how rr rotation is applied consider the tree given in fig which shows an avl tree - - - (ht (hb (ht (ht ( (at ( + (ht ( (bt ( (cnew node height + figure rr rotation in an avl tree example consider the avl tree given in fig and insert into it solution - - - - - (step figure avl tree (step tree (ais an avl tree in tree ( ) new node is inserted in the right sub-tree of the right sub-tree of the critical node (node is the critical node because it is the closest ancestor whose balance factor is not - or )so we apply rr rotation as shown in tree (cnote that the new node has now become part of tree while rotationnode becomes the rootwith and as its left and right child and become the left and right sub-trees of lr and rl rotations consider the avl tree given in fig and see how lr rotation is done to rebalance the tree |
24,540 | data structures using (hb - (hb (ht (hc ( - ( - - ( - ( - (ab (ha ( (bt (ht ( - (cheight (new nodefigure lr rotation in an avl tree example consider the avl tree given in fig tree (ais an avl tree in tree ( ) new node is inserted in the right sub-tree of the left and insert into it sub-tree of the critical node (node is the solution critical node because it is the closest ancestor (step (step whose balance factor is not - or )so we apply lr rotation as shown in tree (cnote that the new node has now become part of - - tree while rotationnode becomes the rootwith and as its left and right children node has and as its left and right sub-trees and and become the left and right sub-trees of node figure avl tree nowconsider the avl tree given in fig and see how rl rotation is done to rebalance the tree - - (ht ( - ( - (hc (hb ( - (at ( - ( (new nodefigure rl rotation in an avl tree - (hc (hb (ht ( - (cheight ( |
24,541 | tree (ais an avl tree in tree ( ) new node is inserted in the left sub-tree of the right sub-tree of the critical node (node is the critical node because it is the closest ancestor whose balance factor is not - or )so we apply rl rotation as shown in tree (cnote that the new node has now become part of tree while rotationnode becomes the rootwith and as its left and right children node has and as its left and right sub-trees and and become the left and right sub-trees of node example construct an avl tree by inserting the following elements in the given order solution (step (step (step - after lr rotation (step (step (step - - - - - (step - (step - - - after ll rotation (step - - - (step figure avl tree deleting node from an avl tree deletion of node in an avl tree is similar to that of binary search trees but it goes one step ahead deletion may disturb the avlness of the treeso to rebalance the avl treewe need to perform rotations there are two classes of rotations that can be performed on an avl tree after deleting given node these rotations are rotation and rotation on deletion of node from the avl treeif node becomes the critical node (closest ancestor node on the path from to the root node that does not have its balance factor as or - )then the type of rotation depends on whether is in the left sub-tree of or in its right sub-tree if the |
24,542 | data structures using node to be deleted is present in the left sub-tree of athen rotation is appliedelse if is in the right sub-treer rotation is performed furtherthere are three categories of and rotations the variations of rotation are - and rotation correspondingly for rotationthere are - and rotations in this sectionwe will discuss only rotation rotations are the mirror images of rotations rotation let be the root of the left or right sub-tree of (critical noder rotation is applied if the balance factor of is this is illustrated in fig (hb (ht ( - ( - (ht ( ( ( (ha (ht ( - (cfigure rotation in an avl tree tree (ais an avl tree in tree ( )the node is to be deleted from the right sub-tree of the critical node (node is the critical node because it is the closest ancestor whose balance factor is not - or since the balance factor of node is we apply rotation as shown in tree (cduring the process of rotationnode becomes the rootwith and as its left and right child and become the left and right sub-trees of rotation let be the root of the left or right sub-tree of (critical noder rotation is applied if the balance factor of is observe that and rotations are similar to ll rotationsthe only difference is that and rotations yield different balance factors this is illustrated in example consider the avl tree given in fig fig and delete from it tree (ais an avl tree in tree ( )the solution node is to be deleted from the right sub-tree of the critical node (node is - the critical node because it is the closest ancestor whose balance factor is not - - or since the balance factor of node - - - is we apply rotation as shown in tree ( during the process of rotationnode becomes the rootwith and as its left and (step (step right children and become the left and figure avl tree right sub-trees of |
24,543 | (hb ( - ( - (hb (ht ( - ( (aa ( - (bt ( - (cfigure rotation in an avl tree example solution consider the avl tree given in fig and delete from it - (step (step figure avl tree - rotation let be the root of the left or right sub-tree of (critical noder- rotation is applied if the balance factor of is - observe that - rotation is similar to lr rotation this is illustrated in fig - - (hb ( - ( - ( - ( - ( - ( - (ac (bb ( - ( - ( - ( - ( - (cfigure rotation in an avl tree tree (ais an avl tree in tree ( )the node is to be deleted from the right sub-tree of the critical node (node is the critical node because it is the closest ancestor whose balance factor is not - or since the balance factor of node is - we apply - rotation as shown in tree ( |
24,544 | data structures using while rotationnode becomes the rootwith and as its left and right child and become the left and right sub-trees of example consider the avl tree given in fig and delete from it solution (step - - - (step figure avl tree example solution delete nodes and from the avl tree given in fig (step figure avl tree write program that shows insertion operation in an avl tree #include typedef enum false ,true boolstruct node int valint balancestruct node *left_childstruct node *right_child}struct nodesearch(struct node *ptrint dataif(ptr!=nullif(data valptr search(ptr -left_child,data)else ifdata ptr -valptr search(ptr -right_childdata)return(ptr)struct node *insert (int datastruct node *ptrint *ht_incstruct node *aptr programming example (step - (step (step |
24,545 | struct node *bptrif(ptr==nullptr (struct node *malloc(sizeof(struct node))ptr -val dataptr -left_child nullptr -right_child nullptr -balance *ht_inc truereturn (ptr)if(data valptr -left_child insert(dataptr -left_childht_inc)if(*ht_inc==trueswitch(ptr -balancecase - /right heavy *ptr -balance *ht_inc falsebreakcase /balanced *ptr -balance breakcase /left heavy *aptr ptr -left_childif(aptr -balance = printf("left to left rotation\ ")ptr -left_childaptr -right_childaptr -right_child ptrptr -balance aptr -balance= ptr aptrelse printf("left to right rotation\ ")bptr aptr -right_childaptr -right_child bptr -left_childbptr -left_child aptrptr -left_child bptr -right_childbptr -right_child ptrif(bptr -balance = ptr -balance - else ptr -balance if(bptr -balance =- aptr -balance else aptr -balance bptr -balance= ptr bptr*ht_inc falseif(data ptr -val |
24,546 | data structures using ptr -right_child insert(infoptr -right_childht_inc)if(*ht_inc==trueswitch(ptr -balancecase /left heavy *ptr -balance *ht_inc falsebreakcase /balanced *ptr -balance - breakcase - /right heavy *aptr ptr -right_childif(aptr -balance =- printf("right to right rotation\ ")ptr -right_childaptr -left_childaptr -left_child ptrptr -balance aptr -balance= ptr aptrelse printf("right to left rotation\ ")bptr aptr -left_childaptr -left_child bptr -right_childbptr -right_child aptrptr -right_child bptr -left_childbptr -left_child pptrif(bptr -balance =- ptr -balance else ptr -balance if(bptr -balance = aptr -balance - else aptr -balance bptr -balance= ptr bptr}/*end of else**ht_inc falsereturn(ptr)void display(struct node *ptrint levelint iif ptr!=null display(ptr -right_childlevel+ )printf("\ ")for ( leveli++printf(")printf("% "ptr -val)display(ptr -left_childlevel+ ) |
24,547 | void inorder(struct node *ptrif(ptr!=nullinorder(ptr -left_child)printf("% ",ptr -val)inorder(ptr -right_child)main(bool ht_incint data int optionstruct node *root (struct node *)malloc(sizeof(struct node))root nullwhile( printf(" insert\ ")printf(" display\ ")printf(" quit\ ")printf("enter your option ")scanf("% ",&option)switch(choicecase printf("enter the value to be inserted ")scanf("% "&data)ifsearch(root,data=null root insert(dataroot&ht_inc)else printf("duplicate value ignored\ ")breakcase if(root==nullprintf("tree is empty\ ")continueprintf("tree is :\ ")display(root )printf("\ \ ")printf("inorder traversal is")inorder(root)printf("\ ")breakcase exit( )defaultprintf("wrong option\ ") red-black trees red-black tree is self-balancing binary search tree that was invented in by rudolf bayer who called it the 'symmetric binary -treealthough red-black tree is complexit has good worst |
24,548 | data structures using case running time for its operations and is efficient to use as searchinginsertionand deletion can all be done in (log ntimewhere is the number of nodes in the tree practicallya red-black tree is binary search tree which inserts and removes intelligentlyto keep the tree reasonably balanced special point to note about the red-black tree is that in this treeno data is stored in the leaf nodes properties of red-black trees red-black tree is binary search tree in which every node has colour which is either red or black apart from the other restrictions of binary search treethe red-black tree has the following additional requirements the colour of node is either red or black the colour of the root node is always black all leaf nodes are black every red node has both the children coloured in black every simple path from given node to any of its leaf nodes has an equal number of black nodes look at fig which shows red-black tree black red null null null null null null null null null null null figure red-black tree these constraints enforce critical property of red-black trees the longest path from the root node to any leaf node is no more than twice as long as the shortest path from the root to any other leaf in that tree this results in roughly balanced tree since operations such as insertiondeletionand searching require worst-case times proportional to the height of the treethis theoretical upper bound on the height allows red-black trees to be efficient in the worst caseunlike ordinary binary search trees to understand the importance of these propertiesit suffices to note that according to property no path can have two red nodes in row the shortest possible path will have all black nodesand the longest possible path would alternately have red and black node since all maximal paths have the same number of black nodes (property )no path is more than twice as long as any other path figure shows some binary search trees that are not red-black trees |
24,549 | (root is red in colour null null null null null null null null ( null null null null null null null null null null null ( null null null null figure trees null (non-black leaf nodenull (cnull (firstevery red node does not have both the children coloured in black secondevery simple path from given node to any of its leaf nodes does not have equal number of black nodes null null null null null null null |
24,550 | data structures using operations on red-black trees preforming read-only operation (like traversing the nodes in treeon red-black tree requires no modification from those used for binary search trees remember that every red-black tree is special case of binary search tree howeverinsertion and deletion operations may violate the properties of red-black tree thereforethese operations may create need to restore the redblack properties that may require small number of ( (log nor amortized ( )colour changes inserting node in red-black tree the insertion operation starts in the same way as we add new node in the binary search tree howeverin binary search treewe always add the new node as leafwhile in red-black treeleaf nodes contain no data so instead of adding the new node as leaf nodewe add red interior node that has two black leaf nodes note that the colour of the new node is red and its leaf nodes are coloured in black once new node is addedit may violate some properties of the red-black tree so in order to restore their propertywe check for certain cases and restore the property depending on the case that turns up after insertion but before learning these cases in detailfirst let us discuss certain important terms that will be used grandparent node (gof node (nrefers to the parent of ' parent ( )as in human family trees the code to find node' grandparent can be given as followsstruct node grand_parent(struct node * /no parent means no grandparent if (( !null&( -parent !null)return -parent -parentelse return nulluncle node (uof node (nrefers to the sibling of ' parent ( )as in human family trees the code to find node' uncle can be given as followsstruct node *uncle(struct node *nstruct node *gg grand_parent( )//with no grandparentthere cannot be any uncle if ( =nullreturn nullif ( -parent = -leftreturn -rightelse return -leftwhen we insert new node in red-black treenote the followingall leaf nodes are always black so property always holds true property (both children of every red node are blackis threatened only by adding red noderepainting black node redor rotation property (all paths from any given node to its leaf nodes has equal number of black nodesis threatened only by adding black noderepainting red node blackor rotation |
24,551 | case the new node is added as the root of the tree in this casen is repainted blackas the root of the tree is always black since adds one black node to every path at onceproperty is not violated the code for case can be given as followsvoid case (struct node *nif ( -parent =null/root node -colour blackelse case ( )case the new node' parent is black in this caseboth children of every red node are blackso property is not invalidated property is also not threatened this is because the new node has two black leaf childrenbut because is redthe paths through each of its children have the same number of black nodes the code to check for case can be given as followsvoid case (struct node *nif ( -parent -colour =blackreturn/red black tree property is not violated*else case ( )in the following casesit is assumed that has grandparent node gbecause its parent is redand if it were the rootit would be black thusn also has an uncle node (irrespective of whether is leaf node or an internal nodecase if both the parent (pand the uncle (uare red in this caseproperty which says all paths from any given node to its leaf nodes have an equal number of black nodes is violated insertion in the third case is illustrated in fig in order to restore property both nodes ( and uare repainted black and the grandparent is repainted red nowthe new red node has black parent since any path through the parent or uncle must pass through the grandparentthe number of black nodes on these paths has not changed howeverthe grandparent may now violate property which says that the root node is always black or property which states that both children of every red node are black property will be violated when has red parent in order to fix this problemthis entire procedure is recursively performed on from case the code to deal with figure insertion in case case insertion is as follows |
24,552 | data structures using void case (struct node *nstruct node * *gu uncle ( ) grand_parent( )if (( !null&( -colour =red) -parent -colour blacku -colour blackg -colour redcase ( )else insert_case ( )note in the remaining caseswe assume that the parent node is the left child of its parent if it is the right childthen interchange left and right in cases and case the parent is red but the uncle is black and is the right child of and is the left child of in order to fix this problema left rotation is done to switch the roles of the new node and its parent after the rotationnote that in the codewe have re-labelled and and thencase is called to deal with the new node' parent this is done because property which says both children of every red node should be black is still violated figure illustrates case insertion note that in case is the left child of and is the right child of gwe have to perform right rotation in the code that handles case we check for and and thenperform either left or right rotation figure insertion in case void case (struct node *nstruct node * grand_ parent( )if (( = -parent -right&( -parent = -left)rotate_left( -parent) -leftelse if (( = -parent -left&( -parent = -right)rotate_right( -parent) -rightcase ( )case the parent is red but the uncle is black and the new node is the left child of pand is the left child of its parent in order to fix this problema right rotation on (the grandparent of nis performed after this rotationthe former parent is now the parent of both the new node and the former grandparent we know that the colour of is black (because otherwise its former child could not have been red)so now switch the colours of and so that the resulting tree satisfies property which states that both children of red node are black case insertion is illustrated in fig |
24,553 | figure insertion in case note that in case is the right child of and is the right child of gwe perform left rotation in the code that handles case we check for and and thenperform either left or right rotation void case (struct node *nstruct node *gg grandparent( )if (( = -parent -left&( -parent = -left)rotate_right( )else if (( = -parent -right&( -parent = -right)rotate_left( ) -parent -colour blackg -colour reddeleting node from red-black tree we start deleting node from red-black tree in the same way as we do in case of binary search tree in binary search treewhen we delete node with two non-leaf childrenwe find either the maximum element in its left sub-tree of the node or the minimum element in its right sub-treeand move its value into the node being deleted after thatwe delete the node from which we had copied the value note that this node must have less than two non-leaf children thereforemerely copying value does not violate any red-black propertiesbut it just reduces the problem of deleting to the problem of deleting node with at most one non-leaf child in this sectionwe will assume that we are deleting node with at most one non-leaf childwhich we will call its child in case this node has both leaf childrenthen let one of them be its child while deleting nodeif its colour is redthen we can simply replace it with its childwhich must be black all paths through the deleted node will simply pass through one less red nodeand both the deleted node' parent and child must be blackso none of the properties will be violated another simple case is when we delete black node that has red child in this caseproperty and property could be violatedso to restore themjust repaint the deleted node' child with black howevera complex situation arises when both the node to be deleted as well as its child is black in this casewe begin by replacing the node to be deleted with its child in the codewe label the child node as (in its new positionnand its sibling (its new parent' other childas the code to find the sibling of node can be given as followsstruct node *sibling(struct node *nif ( = -parent -leftreturn -parent -rightelse |
24,554 | data structures using return -parent -leftwe can start the deletion process by using the following codewhere the function replace_node substitutes the child into ' place in the tree for conveniencewe assume that null leaves are represented by actual node objectsrather than null void delete_child(struct node * /if has at most one non-null child *struct node *childif (is_leaf( -right)child -leftelse child -rightreplace_node(nchild)if ( -colour =blackif (child -colour =redchild -colour blackelse del_case (child)free( )when both and its parent are blackthen deleting will cause paths which precede through to have one fewer black nodes than the other paths this will violate property thereforethe tree needs to be rebalanced there are several cases to considerwhich are discussed below case is the new root in this casewe have removed one black node from every pathand the new root is blackso none of the properties are violated void del_case (struct node *nif ( -parent !nulldel_case ( )note in cases and we assume is the left child of its parent if it is the right childleft and right should be interchanged throughout these three cases case sibling is red in this caseinterchange the colours of and sand then rotate left at in the resultant trees will become ' grandparent figure illustrates case deletion sl sr sr sl figure deletion in case |
24,555 | the code that handles case deletion can be given as followsvoid del_case (struct node *nstruct node *ss sibling( )if ( -colour =redif ( = -parent -leftrotate_left( -parent)else rotate_right( -parent) -parent -colour reds -colour blackdel_case ( )case psand ' children are black in this casesimply repaint with red in the resultant treeall the paths passing through will have one less black node thereforeall the paths that pass through now have one fewer black nodes than the paths that do not pass through pso property is still violated to fix this problemwe perform the rebalancing procedure on pstarting at case case is illustrated in fig sr sl sr sl figure insertion in case the code for case can be given as followsvoid del_case (struct node *nstruct node *ss sibling( )if (( -parent -colour =black&( -colour =black&( -left -colour =black&( -right -colour =black) -colour reddel_case ( -parent)else del_case ( )case and ' children are blackbut is red in this casewe interchange the colours of and although this will not affect the number of black nodes on the paths going through sit will add one black node to the paths going through nmaking up for the deleted black node on those paths figure illustrates this case |
24,556 | data structures using sl sr sr sl figure insertion in case the code to handle case is as followsvoid del_case (struct node *nstruct node *ss sibling( ) - - - ( -left -colour =black&( -right -colour =black) -colour redn -parent -colour blackelse del_case ( )sl sl sr sr figure insertion in case =black&case is the left child of and is blacks' left child is reds' right child is black in this caseperform right rotation at after the rotations' left child becomes ' parent and ' new sibling alsointerchange the colours of and its new parent note that now all paths still have equal number of black nodesbut has black sibling whose right child is redso we fall into case refer fig the code to handle case is given as followsvoid del_case (struct node *nstruct node *ss sibling( )if ( -colour =black/the following code forces the red to be on the left of the left of the parentor right of the rightto be correctly operated in case *if (( = -parent -left&( -right -colour =black&( -left -colour =red)rotate_right( )else if (( = -parent -right&( -left -colour =black&( -right -colour =red)rotate_left( ) |
24,557 | -colour reds -right -colour blackdel_case ( ) sr figure sr insertion in case case is blacks' right child is redand is the left child of its parent in this casea left rotation is done at to make the parent of and ' right child after the rotationthe colours of and are interchanged and ' right child is coloured black once these steps are followedyou will observe that property and property remain valid case is explained in fig the code to fix case can be given as followsvoid del_case (struct node *nstruct node *ss sibling( ) -colour -parent -colourn -parent -colour blackif ( = -parent -lefts -right -colour blackrotate_left( -parent)else -left -colour blackrotate_right( -parent)applications of red-black trees red-black trees are efficient binary search treesas they offer worst case time guarantee for insertiondeletionand search operations red-black trees are not only valuable in time-sensitive applications such as real-time applicationsbut are also preferred to be used as building block in other data structures which provide worst-case guarantee avl trees also support (log nsearchinsertionand deletion operationsbut they are more rigidly balanced than red-black treesthereby resulting in slower insertion and removal but faster retrieval of data splay trees splay trees were invented by daniel sleator and robert tarjan splay tree is self-balancing binary search tree with an additional property that recently accessed elements can be re-accessed fast it is said to be an efficient binary tree because it performs basic operations such as insertionsearchand deletion in (log( )amortized time for many non-uniform sequences of operationssplay trees perform better than other search treeseven when the specific pattern of the sequence is unknown splay tree consists of binary treewith no additional fields when node in splay tree is accessedit is rotated or 'splayedto the rootthereby changing the structure of the tree since the |
24,558 | most frequently accessed node is always moved closer to the starting point of the search (or the root node)these nodes are therefore located faster simple idea behind it is that if an element is accessedit is likely that it will be accessed again in splay treeoperations such as insertionsearchand deletion are combined with one basic operation called splaying splaying the tree for particular node rearranges the tree to place that node at the root technique to do this is to first perform standard binary tree search for that node and then use rotations in specific order to bring the node on top operations on splay trees in this sectionwe will discuss the four main operations that are performed on splay tree these include splayinginsertionsearchand deletion splaying when we access node nsplaying is performed on to move it to the root to perform splay operationcertain splay steps are performed where each step moves closer to the root splaying particular node of interest after every access ensures that the recently accessed nodes are kept closer to the root and the tree remains roughly balancedso that the desired amortized time bounds can be achieved each splay step depends on three factorswhether is the left or right child of its parent pwhether is the root or notand if notwhether is the left or right child of its parentg ( ' grandparentdepending on these three factorswe have one splay step based on each factor zig step the zig operation is done when (the parent of nis the root of the splay tree in the zig stepthe tree is rotated on the edge between and zig step is usually performed as the last step in splay operation and only when has an odd depth at the beginning of the operation refer fig zig-zig step the zig-zig operation is performed when is not the root in addition to thisn and are either both right or left children of their parents figure shows the case where and are the left children during the zig-zig stepfirst the tree is rotated on the edge joining and its parent gand then again rotated on the edge joining and figure zig step figure zig-zig step |
24,559 | zig-zag step the zig-zag operation is performed when is not the root in addition to thisn is the right child of and is the left child of or vice versa in zig-zag stepthe tree is first rotated on the edge between and pand then rotated on the edge between and refer fig figure zig-zag step inserting node in splay tree although the process of inserting new node into splay tree begins in the same way as we insert node in binary search treebut after the insertionn is made the new root of the splay tree the steps performed to insert new node in splay tree can be given as followsstep search in the splay tree if the search is successfulsplay at the node step if the search is unsuccessfuladd the new node in such way that it replaces the null pointer reached during the search by pointer to new node splay the tree at example consider the splay tree given on the left observe the change in its structure when is added to it solution zig-zag step ( ( ( ( note node to get the final splay treefirst apply zig-zag step on then apply zig-zag step to make the root |
24,560 | data structures using example consider the splay tree given in fig searching for node in splay tree observe the change in its structure when node containing if particular node is present in the splay treethen pointer to is returned is searched in the tree otherwise pointer to the null node is returned the steps performed to search node in splay tree include ( ( ( figure splay tree search down the root of the splay tree looking for if the search is successfuland we reach nthen splay the tree at and return pointer to if the search is unsuccessfuli the splay tree does not contain nthen we reach null node splay the tree at the last non-null node reached during the search and return pointer to null deleting node from splay tree to delete node from splay treewe perform the following stepssearch for that has to be deleted if the search is unsuccessfulsplay the tree at the last non-null node encountered during the search if the search is successful and is not the root nodethen let be the parent of replace by an appropriate descendent of (as we do in binary search treefinally splay the tree at advantages and disadvantages of splay trees the advantages of using splay tree area splay tree gives good performance for searchinsertionand deletion operations this advantage centres on the fact that the splay tree is self-balancing and self-optimizing data structure in which the frequently accessed nodes are moved closer to the root so that they can be accessed quickly this advantage is particularly useful for implementing caches and garbage collection algorithms splay trees are considerably simpler to implement than the other self-balancing ( (bbinary search treessuch as red-black trees or avl treeswhile their averagefigure (asplay tree (bsplay tree case performance is just as efficient splay trees minimize memory requirements as they do not store any book-keeping data unlike other types of self-balancing treessplay trees provide good performance (amortized (log )with nodes containing identical keys example consider the splay tree at the left when we delete node from itthe new structure of the tree can be given as shown in the right side of fig (aafter splaying the tree at pthe resultant tree will be as shown in fig ( ) |
24,561 | howeverthe demerits of splay trees includewhile sequentially accessing all the nodes of tree in sorted orderthe resultant tree becomes completely unbalanced this takes accesses of the tree in which each access takes (log ntime for examplere-accessing the first node triggers an operation that in turn takes (noperations to rebalance the tree before returning the first node although this creates significant delay for the final operationthe amortized performance over the entire sequence is still (log nfor uniform accessthe performance of splay tree will be considerably worse than somewhat balanced simple binary search tree for uniform accessunlike splay treesthese other data structures provide worst-case time guarantees and can be more efficient to use points to remember binary search treealso known as an ordered binary treeis variant of binary tree in which all the nodes in the left sub-tree have value less than that of the root node and all the nodes in the right sub-tree have value either equal to or greater than the root node the average running time of search operation is (log nhoweverin the worst casea binary search tree will take (ntime to search an element from the tree mirror image of binary search tree is obtained by interchanging the left sub-tree with the right sub-tree at every node of the tree in threaded binary treenull entries can be replaced to store pointer to either the in-order predecessor or in-order successor of node one-way threaded tree is also called single threaded tree in two-way threaded treealso called double threaded treethreads will appear in both the left and the right field of the node an avl tree is self-balancing tree which is also known as height-balanced tree each node has balance factor associated with itwhich is calculated by subtracting the height of the right sub-tree from the height of the left sub-tree in height balanced treeevery node has balance factor of either or - red-black tree is self-balancing binary search tree which is also called as 'symmetric binary -treealthough red-black tree is complexit has good worst case running time for its operations and is efficient to useas searchinginsertionand deletion can all be done in (log ntime splay tree is self-balancing binary search tree with an additional property that recently accessed elements can be re-accessed fast exercises review questions explain the concept of binary search trees explain the operations on binary search trees how does the height of binary search tree affect its performance how many nodes will complete binary tree with nodes have in the last levelwhat will be the height of the tree write short note on threaded binary trees why are threaded binary trees called efficient binary treesgive the merits of using threaded binary tree discuss the advantages of an avl tree how is an avl tree better than binary search tree how does red-black tree perform better than binary search tree list the merits and demerits of splay tree create binary search tree with the input given below (ainsert and into the tree (bdelete values and from the tree |
24,562 | data structures using consider the binary search tree given below now do the following operationsfind the result of in-orderpre-orderand post-order traversals show the deletion of the root node insert and in the tree balance the avl trees given below create an avl tree using the following sequence of data draw all possible binary search trees of and programming exercises consider the avl tree given below and insert and in it delete nodes and from the avl tree formed after solving the above question - - discuss the properties of red-black tree explain the insertion cases explain splay trees in detail with relevant examples provide the memory representation of the binary tree given belowfind the result of one-way in-orderone-way pre-orderand two-way in-order threading of the tree in each casedraw the tree and also give its memory representation multiple-choice questions in the worst casea binary search tree will take how much time to search an element(ao( (bo(log (co( (do( log how much time does an avl tree take to perform searchinsertand delete operations in the average case as well as the worst case(ao( (bo(log (co( (do( log when the left sub-tree of the tree is one level higher than that of the right sub-treethen the balance factor is ( ( ( - ( which rotation is done when the new node is inserted in the right sub-tree of the right sub-tree of the critical node(all (blr (crl (drr when node is accessed it is splayed to make it the (aroot node (bparent node (cchild node (dsibling node true or false write program to insert and delete values from binary search tree write program to count the number of nodes in binary search tree in binary search treeall the nodes in the left sub-tree have value less than that of the root node |
24,563 | if we take two empty binary search trees and insert the same elements but in different orderthen the resultant trees will be the same when we insert new node in binary search treeit will be added as an internal node mirror image of binary search tree is obtained by interchanging the left sub-tree with the right sub-tree at every node of the tree if the thread appears in the right fieldthen it will point to the in-order successor of the node if the node to be deleted is present in the left subtree of athen rotation is applied height of an avl tree is limited to (log critical node is the nearest ancestor node on the path from the root to the inserted node whose balance factor is - or rl rotation is done when the new node is inserted in the right sub-tree of the right sub-tree of the critical node in red-black treesome leaf nodes can be red fill in the blanks is also called fully threaded binary tree to find the node with the largest valuewe will find the value of the rightmost node of the if the thread appears in the right fieldthen it will point to the of the node the balance factor of node is calculated by balance factor - means searching an avl tree takes time rotation is done when the new node is inserted in the left sub-tree of the left sub-tree of the critical node in red-black treethe colour of the root node is and the colour of leaf node is the zig operation is done when in splay treesrotation is analogous to operation |
24,564 | multi-way search trees learning objective in this we will study about multi-way search trees which are quite different from other binary search trees though the concept is similar to normal binary search treesbut -way search trees can store more than one key values in single node the starts with general description of -way search treesand then discusses in detail -way search trees such as treesbtreesand - trees introduction we have discussed that every node in binary search tree contains one value and two pointersleft and rightwhich point to the node' left and right sub-treesrespectively the structure of binary search tree node is shown in fig the same concept is used in an -way search tree which has values per node and subtrees in such treem is called the degree of the tree pointer to note that in binary search tree so it has one value pointer to value or key right sub-tree left sub-tree of the node and two sub-trees in other wordsevery internal node of an -way search tree consists of pointers to sub-trees figure structure of binary search tree node and contains keyswhere the structure of an -way search tree node is shown in fig pn- kn- pn figure structure of an -way search tree node in the structure shownp pn are pointers to the node' sub-trees and kn- are the key values of the node all the key values are stored in ascending order that iski ki+ for ps ps - |
24,565 | in an -way search treeit is not compulsory that every node has exactly - values and subtrees ratherthe node can have anywhere from to - valuesand the number of sub-trees can vary from (for leaf nodeto where is the number of key values in the node is thus fixed figure -way search tree of order upper limit that defines how many key values can be stored in the node consider the -way search tree shown in fig here so node can store maximum of two key values and can contain pointers to three sub-trees in our examplewe have taken very small value of so that the concept becomes easier for the readerbut in practicem is usually very large using -way search treelet us lay down some of the basic properties of an -way search tree note that the key values in the sub-tree pointed by are less than the key value similarlyall the key values in the sub-tree pointed by are less than so on and so forth thusthe generalized rule is that all the key values in the sub-tree pointed by pi are less than kiwhere ps ps - note that the key values in the sub-tree pointed by are greater than the key value similarlyall the key values in the sub-tree pointed by are greater than so on and so forth thusthe generalized rule is that all the key values in the sub-tree pointed by pi are greater than ki- where ps ps - in an -way search treeevery sub-tree is also an -way search tree and follows the same rules trees tree is specialized -way tree developed by rudolf bayer and ed mccreight in that is widely used for disk access tree of order can have maximum of - keys and pointers to its sub-trees tree may contain large number of key values and pointers to sub-trees storing large number of keys in single node keeps the height of the tree relatively small tree is designed to store sorted data and allows searchinsertionand deletion operations to be performed in logarithmic amortized time tree of order (the maximum number of children that each node can haveis tree with all the properties of an -way search tree in addition it has the following properties every node in the tree has at most (maximumm children every node in the tree except the root node and leaf nodes has at least (minimumm/ children this condition helps to keep the tree bushy so that the path from the root node to the leaf is very shorteven in tree that stores lot of data the root node has at least two children if it is not terminal (leafnode all leaf nodes are at the same level an internal node in the tree can have number of childrenwhere ps ps it is not necessary that every node has the same number of childrenbut the only restriction is that the node should have at least / children as tree of order is given in fig figure tree of order |
24,566 | while performing insertion and deletion operations in treethe number of child nodes may change soin order to maintain minimum number of childrenthe internal nodes may be joined or split we will discuss searchinsertionand deletion operations in this section searching for an element in tree searching for an element in tree is similar to that in binary search trees consider the tree given in fig to search for we begin at the root node the root node has value which is less than sowe traverse in the right sub-tree the right sub-tree of the root node has two key values and since ps ps we traverse the right sub-tree of that isthe left sub-tree of this sub-tree has three values and on finding the value the search is successful take another example if you want to search for then we traverse the left sub-tree of the root node the left sub-tree has two key values and againwe traverse the left sub-tree of we find that it has two key values and there is no left sub-tree of hence the value is not stored in the tree since the running time of the search operation depends upon the height of the treethe algorithm to search for an element in tree takes (logt ntime to execute inserting new element in tree in treeall insertions are done at the leaf node level new value is inserted in the tree using the algorithm given below search the tree to find the leaf node where the new key value should be inserted if the leaf node is not fullthat isit contains less than - key valuesthen insert the new element in the node keeping the node' elements ordered if the leaf node is fullthat isthe leaf node already contains - key valuesthen (ainsert the new value in order into the existing set of keys(bsplit the node at its median into two nodes (note that the split nodes are half full)and (cpush the median element up to its parent' node if the parent' node is already fullthen split the parent node by following the same steps example look at the tree of order given below and insert and into it step insert step insert figure ( |
24,567 | till nowwe have easily inserted and in the tree because the leaf nodes were not full but nowthe node in which should be inserted is already full as it contains four values here we split the nodes to form two separate nodes but before splittingarrange the key values in order (including the new valuethe ordered set of values is given as and the median value is so push into its parent' node and split the leaf nodes step insert figure (bnow the node in which should be inserted is already full as it contains four key values here we split the nodes to form two separate nodes but before splittingwe arrange the key values in order (including the new valuethe ordered set of values is given as and the median value is so we push into its parent' node and split the leaf nodes but againwe see that the parent' node is already fullso we split the parent node using the same procedure step insert figure (cb tree deleting an element from tree like insertiondeletion is also done from the leaf nodes there are two cases of deletion in the first casea leaf node has to be deleted in the second casean internal node has to be deleted let us first see the steps involved in deleting leaf node locate the leaf node which has to be deleted if the leaf node contains more than the minimum number of key values (more than / elements)then delete the value else if the leaf node does not contain / elementsthen fill the node by taking an element either from the left or from the right sibling (aif the left sibling has more than the minimum number of key valuespush its largest key into its parent' node and pull down the intervening element from the parent node to the leaf node where the key is deleted (belseif the right sibling has more than the minimum number of key valuespush its smallest key into its parent node and pull down the intervening element from the parent node to the leaf node where the key is deleted elseif both left and right siblings contain only the minimum number of elementsthen create new leaf node by combining the two leaf nodes and the intervening element of the parent node (ensuring that the number of elements does not exceed the maximum number of elements node can havethat ismif pulling the intervening element from the parent node leaves it with less than the minimum number of keys in the nodethen propagate the process upwardsthereby reducing the height of the tree |
24,568 | to delete an internal nodepromote the successor or predecessor of the key to be deleted to occupy the position of the deleted key this predecessor or successor will always be in the leaf node so the processing will be done as if value from the leaf node has been deleted example consider the following tree of order and delete values and from it (fig ( ) step delete step delete step delete step delete figure tree example consider the tree of order given below and perform the following operations(ainsert and then (bdelete |
24,569 | step insert step delete step insert step delete figure tree example create tree of order by inserting the following elements and step insert step insert step insert step insert step insert step insert step insert (contd |
24,570 | data structures using step insert step insert figure tree applications of trees database is collection of related data the prime reason for using database is that it stores organized data to facilitate its users to updateretrieveand manage the data the data stored in the database may include namesaddressespicturesand numbers for examplea teacher may wish to maintain database of all the students that includes the namesroll numbersdate of birthand marks obtained by every student nowadaysdatabases are used in every industry to store hundreds of millions of records in the real worldit is not uncommon for database to store gigabytes and terabytes of data for examplea telecommunication company maintains customer billing database with more than billion rows that contains terabytes of data we know that primary memory is very expensive and is capable of storing very little data as compared to secondary memory devices like magnetic disks alsoram is volatile in nature and we cannot store all the data in primary memory we have no other option but to store data on secondary storage devices but accessing data from magnetic disks is , to , , times slower than accessing it from the main memory sob trees are often used to index the data and provide fast access consider situation in which we have to search an un-indexed and unsorted database that contains key values the worst case running time to perform this operation would be (nin contrastif the data in the database is indexed with treethe same search operation will run in (log nfor examplesearching for single key on set of one million keys will at most require , , comparisons but if the same data is indexed with tree of order then only comparisons will be required in the worst case hencewe see that indexing large amounts of data can provide significant boost to the performance of search operations when we use trees or generalized -way search treesthe value of or the order of trees is often very large typicallyit varies from - this means that single node in the tree can contain - keys and - pointers to child nodes we take large value of mainly because of three reasons disk access is very slow we should be able to fetch large amount of data in one disk access disk is block-oriented device that isdata is organized and retrieved in terms of blocks so while using tree (generalized -way search tree) large value of is used so that one single node of the tree can occupy the entire block in other wordsm represents the maximum number of data items that can be stored in single block is maximized to speed up processing more the data stored in blocklesser the time needed to move it into the main memory large value minimizes the height of the tree sosearch operation becomes really fast |
24,571 | btrees btree is variant of tree which stores sorted data in way that allows for efficient insertionretrievaland removal of recordseach of which is identified by key while tree can store both keys and records in its interior nodesa btreein contraststores all the records at the leaf level of the treeonly keys are stored in the interior nodes the leaf nodes of btree are often linked to one another in linked list this has an added advantage of making the queries simpler and more efficient typicallybtrees are used to store large amounts of data that cannot be stored in the main memory with btreesthe secondary storage (magnetic diskis used to store the leaf nodes of trees and the internal nodes of trees are stored in the main memory btrees store data only in the leaf nodes all other nodes (internal nodesare called index nodes or -nodes and store index values this allows us to traverse the tree from the root down to the leaf node that stores the desired data item figure shows btree of order figure btree of order many database systems are implemented using btree structure because of its simplicity since all the data appear in the leaf nodes and are orderedthe tree is always balanced and makes searching for data efficient btree can be thought of as multi-level index in which the leaves make up dense index and the non-leaf nodes make up sparse index the advantages of btrees can be given as follows records can be fetched in equal number of disk accesses it can be used to perform wide range of queries easily as leaves are linked to nodes at the upper level height of the tree is less and balanced supports both random and sequential access to records keys are used for indexing comparison between trees and btrees table shows the comparison between trees and btrees table comparison between trees and to btrees tree btree search keys are not repeated stores redundant search key data is stored in internal or leaf nodes data is stored only in leaf nodes searching takes more time as data may be found in leaf or non-leaf node searching data is very easy as the data can be found in leaf nodes only deletion of non-leaf nodes is very complicated deletion is very simple because data will be in the leaf node leaf nodes cannot be stored using linked lists leaf node data are ordered using sequential linked lists the structure and operations are complicated the structure and operations are simple |
24,572 | data structures using inserting new element in btree new element is simply added in the leaf node if there is space for it but if the data node in the tree where insertion has to be done is fullthen that node is split into two nodes this calls for adding new index value in the parent index node so that future queries can arbitrate between the two new nodes howeveradding the new index value in the parent node may cause itin turnto split in factall the nodes on the path from leaf to the root may split when new value is added to leaf node if the root node splitsa new leaf node is created and the tree grows by one level the steps to insert new node in btree are summarized in fig step insert the new node as the leaf node step if the leaf node overflowssplit the node and copy the middle element to next index node step if the index node overflowssplit that node and move the middle element to next index page figure algorithm for inserting new node in btree example consider the btree of order given and insert in it step insert step split the leaf node step split the index node figure inserting node in the given btree deleting an element from btree as in treesdeletion is always done from leaf node if deleting data element leaves that node emptythen the neighbouring nodes are examined and merged with the underfull node this process calls for the deletion of an index value from the parent index node whichin turnmay cause it to become empty similar to the insertion processdeletion may cause merge-delete wave to run from leaf node all the way up to the root this leads to shrinking of the tree by one level the steps to delete node from btree are summarized in fig step step step delete the key and data from the leaves if the leaf node underflowsmerge that node with the sibling and delete the key in between them if the index node underflowsmerge that node with the sibling and move down the key in between them figure algorithm for deleting node from btree |
24,573 | example consider the btree of order given below and delete node from it step delete step leaf node underflows so merge with left sibling and remove key step now index node underflowsso merge with sibling and delete the node figure deleting node from the given btree note insertion and deletion operations are recursive in nature and can cascade up or down the +treet thereby affecting its shape dramatically - trees in the last we have seen that for binary search trees the average-case time for operations like search/insert/delete is (log nand the worst-case time is (nwhere is the number of nodes in the tree howevera balanced tree that has height (log nalways guarantees (log ntime for all three methods typical examples of height balanced trees include avl treesred-black treesb treesand - trees we have already discussed these data structures in the earlier and sectionnow we will discuss - trees in - treeeach interior node has either two or three children nodes with two children are called -nodes the -nodes have one data value and two children nodes with three children are called -nodes the -nodes have two data values and three children (left childmiddle childand right childthis means that - tree is not binary tree in this treeall the leaf nodes are at the same level (bottom levellook at fig which shows - tree figure - tree |
24,574 | searching for an element in - tree the search operation is used to determine whether data value is present in - tree the process of searching value in - tree is very similar to searching value in binary search tree the search for data value starts at the root if and are the two values stored in the root nodethen if move to the left child if > and the node has only two childrenmove to the right child if > and the node has three childrenthen move to the middle child if else to the right child if > at the end of the processthe node with data value is reached if and only if is at this leaf example consider the - tree in fig and search in the tree step as move to the middle child step as move to the left child figure searching for element in the - tree of fig lmr lmr figure (ainserting new element in - tree to insert new value in the - treean appropriate position of the value is located in one of the leaf nodes if after insertion of the new valuethe properties of the - tree do not get violated then insertion is over otherwiseif any property is violated then the violating node must be split (fig splitting node node is split when it has three data values and four children herep is the parent and lmr denote the leftmiddleand right children |
24,575 | example consider the - tree given below and insert the following data values into it figure (bstep insert in the leaf node the tree after insertion can be given as figure (cstep insert in the leaf node the tree after insertion can be given as below note that inserting violates the property of - trees thereforethe node with values and must be split figure (dafter splitting the leaf nodethe tree can be given as below figure (estep insert in the leaf node the tree after insertion can be given as follows figure ( |
24,576 | step insert in the leaf node the tree after insertion can be given as follows figure (gthe leaf node has three data values thereforethe node is violating the properties of the tree and must be split figure (hthe parent node has three data values thereforethe node is violating the properties of the tree and must be split figure (iinserting values in the given - tree deleting an element from - tree in the deletion processa specified data value is deleted from the - tree if deleting value from node violates the property of treethat isif node is left with less than one data value then two nodes must be merged together to preserve the general properties of - tree in insertionthe new value had to be added in any of the leaf nodes but in deletion it is not necessary that the value has to be deleted from leaf node the value can be deleted from any of the nodes to delete value xit is replaced by its in-order successor and then removed if node becomes empty after deleting valueit is then merged with another node to restore the property of the tree example consider the - tree given below and delete the following values from it figure (ato delete swap it with its in-order successorthat is now comes in the leaf node remove the value from the leaf node |
24,577 | figure (bfigure ( is an internal node to delete this value swap with its in-order successor so that now becomes leaf node remove the value from the leaf node now there is leaf node that has less than data value thereby violating the property of - tree so the node must be merged to merge the nodepull down the lowest data value in the parent' node and merge it with its left sibling figure ( figure ( is present in leaf nodeso the data value can now there is leaf node that has less than data valuethereby violating the property of - tree be easily removed so the node must be merged to merge the nodepull down the lowest data value in the parent' node and merge it with its left sibling figure (ffigure ( is an internal node to delete this value swap with its in-order successor so that now becomes leaf node remove the value from the leaf node now there is leaf node that has less than data valuethereby violating the property of - tree so the node must be merged to merge the nodepull down the lowest data value in the parent' node and merge it with its left sibling figure (han internal node cannot be emptyso now pull down the lowest data value from the parent' node and merge the empty node with its left sibling figure (ideleting values from the given - tree |
24,578 | data structures using trie the term trie has been taken from the word 'retrievala trie is an ordered tree data structurewhich was introduced in the by edward fredkin trie stores keys that are usually strings it is basically -ary position tree am do in contrast to binary search treesnodes in trie do not store the keys ar associated with them rathera node' position in the tree represents art dot the key associated with that node all the descendants of node have arm arc are common prefix of the string associated with that nodeand the root is associated with the empty string figure shows trie figure trie data structure in the given treekeys are listed in the nodes and the values below them note that each complete english word is assigned an arbitrary integer value we can find each of these words by traversing the various branches in the tree until leaf node is encountered any path from the root to leaf represents word advantages relative to binary search tree when compared with binary search treethe trie data structure has the following advantages faster search searching for keys is fasteras searching key of length takes (mtime in the worst case on the other handa binary search tree performs (logncomparisons of keyswhere is the number of nodes in the tree since search time depends on the height of the tree which is logarithmic in the number of keys (if the tree is balanced)the worst case may take ( log ntime in addition to thism approaches log(nin the worst case hencea trie data structure provides faster search mechanism less space trie occupies less spaceespecially when it contains large number of short strings since keys are not stored explicitly and nodes are shared between the keys with common initial subsequencesa trie calls for less space as compared to binary search tree longest prefix-matching trie facilitates the longest-prefix matching which enables us to find the key sharing the longest possible prefix of all unique characters since trie provides more advantagesit can be thought of as good replacement for binary search trees advantages relative to hash table trie can also be used to replace hash table as it provides the following advantagessearching for data in trie is faster in the worst caseo(mtimecompared to an imperfect hash tablediscussed in which may have numerous key collisions trie is free from collision of keys problem unlike hash tablethere is no need to choose hash function or to change it when more keys are added to trie trie can sort the keys using predetermined alphabetical ordering disadvantages the disadvantages of having trie are listed belowin some casestries can be slower than hash tables while searching data this is true in cases when the data is directly accessed on hard disk drive or some other secondary storage device that has high random access time as compared to the main memory |
24,579 | all the key values cannot be easily represented as strings for examplethe same floating point number can be represented as string in multiple ways ( is equivalent to + etc applications tries are commonly used to store dictionary (for exampleon mobile telephonethese applications take advantage of trie' ability to quickly searchinsertand delete the entries tries are also used to implement approximate matching algorithmsincluding those used in spell-checking software points to remember an -way search tree has values per node and sub-trees in such treem is called the degree of the tree -way search tree consists of pointers to sub-trees and contains keyswhere tree of order can have maximum of - keys and pointers to its sub-trees tree may contain large number of key values and pointers to its sub-trees btree is variant of tree which stores sorted data in way that allows for efficient insertionretrievaland removal of recordseach of which is identified by key btree record data at the leaf level of the treeonly keys are stored in interior nodes trie is an ordered tree data structure which stores keys that are usually strings it is basically -ary position tree in contrast to binary search treesnodes in trie do not store the keys associated with them rathera node' position in the tree represents the key associated with that node in - treeeach interior node has either two or three children this means that - tree is not binary tree exercises review questions why is large value of needed in tree compare trees with btrees in what conditions will you prefer btree over tree write short note on trie data structure compare binary search trees with trie alsolist the merits and demerits of using the trie data structure compare hash tables with trie give brief summary of -way search trees consider the tree given below (ainsert and in the tree (bdelete and from the tree write an essay on btrees create btree of order for the following data arriving in sequence ( tree for list down the applications of trees trees of order are full binary trees justify this statement consider the -way search tree given below insert and in the tree thendelete and from it |
24,580 | data structures using true or false ( -way search tree for multiple-choice questions every internal node of an -way search tree consists of pointers to sub-trees and contains how many keys(am (bm- ( (dm+ every node in tree has at most children (am (bm- ( (dm+ which data structure is commonly used to store dictionary(abinary tree (bsplay tree (ctrie (dred black tree in -way search treem stands for (ainternal nodes (bexternal nodes (cdegree of node (dleaf nodes in best casesearching value in binary search tree may take (ao( (bo( log (co(log (do( all leaf nodes in the tree are at the same level btree stores data only in the -nodes tree stores unsorted data every node in the -tree has at most (maximumm- children the leaf nodes of tree are often linked to one another btree stores redundant search key trie is an ordered tree data structure trie uses more space as compared to binary search tree external nodes are called index nodes fill in the blanks an -way search tree consists of pointers to sub-trees and contains keys -tree of order can have maximum of keys and pointers to its sub-trees every node in the -tree except the root node and leaf nodes have at least children in data is stored in internal or leaf nodes balanced tree that has height (log nalways guarantees time for all three methods |
24,581 | heaps learning objective heap is specialized tree-based data structure there are several variants of heaps which are the prototypical implementations of priority queues we have already discussed priority queues in heaps are also crucial in several efficient graph algorithms in this we will discuss three types of heaps--binary heapsbinomial heapsand fibonacci heaps binary heaps binary heap is complete binary tree in which every node satisfies the heap property which states thatif is child of athen key( >key(bthis implies that elements at every node will be either greater than or equal to the element at its left and right child thusthe root node has the highest key value in the heap such heap is commonly known as max-heap alternativelyelements at every node will be either less than or equal to the element at its left and right child thusthe root has the lowest key value such heap is called min-heap figure shows binary min heap and binary max heap the properties of binary heaps are given as followsmin heap max heap since heap is defined as complete figure binary heaps binary treeall its elements can be stored |
24,582 | data structures using sequentially in an array it follows the same rules as that of complete binary tree that isif an element is at position in the arraythen its left child is stored at position and its right child at position + converselyan element at position has its parent stored at position / being complete binary treeall the levels of the tree except the last level are completely filled the height of binary tree is given as log nwhere is the number of elements heaps (also known as partially ordered treesare very popular data structure for implementing priority queues binary heap is useful data structure in which elements can be added randomly but only the element with the highest value is removed in case of max heap and lowest value in case of min heap binary tree is an efficient data structurebut binary heap is more space efficient and simpler inserting new element in binary heap consider max heap with elements inserting new value into the heap is done in the following two steps add the new value at the bottom of in such way that is still complete binary tree but not necessarily heap let the new value rise to its appropriate place in so that now becomes heap as well to do thiscompare the new value with its parent to check if they are in the correct order if they arethen the procedure haltselse the new value and its parent' value are swapped and step is repeated example solution consider the max heap given in fig and insert in it figure binary heap figure binary heap after insertion of the first step says that insert the element in the heap so that the heap is complete binary tree soinsert the new value as the right child of node in the heap this is illustrated in fig nowas per the second steplet the new value rise to its appropriate place in so that becomes heap as well compare with its parent node value if it is less than its parent' valuethen the new node is in its appropriate place and is heap if the new value is greater than that of its parent' nodethen swap the two values repeat the whole process until becomes heap this is illustrated in fig figure heapify the binary heap |
24,583 | example build max heap from the given set of numbers and also draw the memory representation of the heap solution (step (step (step (step (step (step (step (step (step (step (step (step (step figure the memory representation of can be given as shown in fig heap[ heap[ heap[ heap[ heap[ heap[ heap[ heap[ heap[ heap[ figure memory representation of binary heap after discussing the concept behind inserting new value in the heaplet us now look at the algorithm to do so as shown in fig we assume that with elements is stored in array heap val has to be inserted in heap the location of val as it rises in the heap is given by posand par denotes step [add the new value and set its posset pos the location of the parent of val step set heap[nval note that this algorithm inserts single value in step [find appropriate location of valthe heap in order to build heapuse this algorithm repeat steps and while pos step set par pos/ in loop for exampleto build heap with step if heap[pos<heap[par]elementsuse for loop that executes times and then goto step in each passa single value is inserted else swap heap[pos]heap[parthe complexity of this algorithm in the average pos par case is ( this is because binary heap has [end of ifo(log nheight since approximately of the [end of loopelements are leaves and are in the bottom two step return levelsthe new element to be inserted will only move figure algorithm to insert an element in max heap few levels upwards to maintain the heap |
24,584 | data structures using in the worst caseinsertion of single value may take (log ntime andsimilarlyto build heap of elementsthe algorithm will execute in ( log ntime deleting an element from binary heap consider max heap having elements an element is always example consider the max deleted from the root of the heap sodeleting an element from heap shown in fig and delete the heap is done in the following three stepsthe root node' value replace the root node' value with the last node' value solution so that is still complete binary tree but not necessarily heap delete the last node sink down the new root node' value so that satisfies the heap property in this stepinterchange the root node' value with its child node' value (whichever is largest among its children herethe value of root node and the value of the last node soreplace with and delete the last node figure binary heap (step (step (step (step (since is less than interchange the values (since is less than interchange the valuesfigure binary heap after discussing the concept behind deleting the root element from the heaplet us look at the algorithm given in fig we assume that heap with elements is stored using sequential array called heap last is the last element in the heap and ptr left and right denote the step [remove the last node from the heapset last heap[ ]set position of last and its left and right children step [initializationrespectively as it moves down the heap set ptr left right step set heap[ptrlast step repeat steps to while left < step if heap[ptr>heap[leftand heap[ptr>heap[rightgo to step [end of ifstep if heap[right<heap[leftswap heap[ptr]heap[leftset ptr left else swap heap[ptr]heap[rightset ptr right [end of ifstep set left ptr and right left [end of loopstep return figure algorithm to delete the root element from max heap applications of binary heaps binary heaps are mainly applied for sorting an array using heapsort algorithm we will discuss heapsort algorithm in implementing priority queues binary heap implementation of priority queues in we learned about priority queues we have also seen how priority queues can be implemented using linked lists priority queue is similar to queue in which an item is |
24,585 | dequeued (or removedfrom the front howeverunlike regular queuein priority queue the logical order of elements is determined by their priority while the higher priorities max priority elements are added at the front of the queuein priority out elements with lower priority are added at the rear conceptuallywe can think of priority queue as bag of priorities shown in fig in this bag you figure priority queue visualization can insert any priority but you can take out one with the highest value though we can easily implement priority queues using linear arraybut we should first consider the time required to insert an element in the array and then sort it we need (ntime to insert an element and at least ( log ntime to sort the array thereforea better way to implement priority queue is by using binary heap which allows both enqueue and dequeue of elements in (log ntime binomial heaps binomial heap is set of binomial trees that satisfy the binomial heap properties firstlet us discuss what binomial tree is binomial tree is an ordered tree that can be recursively defined as followsa binomial tree of order has single node binomial tree of order has root node whose children are the root nodes of binomial trees of order - - and binomial tree bi has nodes the height of binomial tree bi is look at fig which shows few binomial trees of different orders we can construct binomial tree bi from two binomial trees of order bi- by linking them together in such way that the root of one is the leftmost child of the root of another bi- bi- ( binomial tree bi is collection of binomial trees of order - - (binomial treeb (binomial treeb (binomial treeb (binomial treeb figure binomial trees binomial heap is collection of binomial trees that satisfy the following propertiesevery binomial tree in satisfies the minimum heap property ( the key of node is either greater than or equal to the key of its parentthere can be one or zero binomial trees for each order including zero order |
24,586 | data structures using according to the first propertythe root of heap-ordered tree contains the smallest key in the tree the second propertyon the other handimplies that binomial heap having nodes contains at most log ( binomial trees linked representation of binomial heaps each node in binomial heap has val field that stores its value in additioneach node has following pointersp[nthat points to the parent of child[nthat points to the leftmost child sibling[nthat points to the sibling of which is immediately to its right if is the root nodethen [nnull if has no childrenthen head [ child[nnulland if is the rightmost child of its parentthen sibling[nnil in addition to thisevery node has degree field which stores the number of children of look at the binomial heap shown in fig figure shows its corresponding linked representation figure binomial heap parent null null null child head [hvalue degree sibling null null null null null null null null null null null null figure linked representation of the binomial tree shown in fig operations on binomial heaps in this sectionwe will discuss the different operations that can be performed on binomial heaps creating new binomial heap the procedure create_binomial-heap(allocates and returns an object hwhere head[his set to null the running time of this procedure can be given as ( finding the node with minimum key the procedure min_binomial-heap(returns pointer to the node which has the minimum value in the binomial heap the algorithm for min_binomial-heap(is shown in fig |
24,587 | min_binomial-heap(hstep [initializationset nullx head[hand min step repeat steps and while null step if val[xmin set min val[xset [end of ifstep set sibling[ [end of loopstep return figure algorithm to find the node with minimum value we have already discussed that binomial heap is heap-orderedthereforethe node with the minimum value in particular binomial tree will appear as root node in the binomial heap thusthe min_ binomial-heap(procedure checks all roots since there are at most log ( roots to checkthe running time of this procedure is (log nexample this case head [hconsider the binomial heap given below and see how the procedure works in head [hx step (min (initiallywe have min * head [hx head [hy step step (min (min figure binomial heap uniting two binomial heaps the procedure of uniting two binomial heaps is used as subroutine by other operations the union_binomial-heap(procedure links together binomial link_binomial-tree(yztrees whose roots have the same degree the algorithm to link bi- tree rooted at node to the bi- tree rooted at node step set parent[yz step set sibling[ychild[zzmaking the parent of yis shown in fig step set child[zy the link_binomial-tree(procedure makes the new step set degree[zdegree[ ] head of the linked list of node ' children in ( time step end the algorithm to unite two binomial heaps and is figure algorithm to link two binomial trees given in fig |
24,588 | data structures using the algorithm destroys the original representations of heaps and apart step set create_binomial-heap(from link_binomial-tree()it uses another step set head[hmerge_binomial-heap( procedure merge_binomial-heap(which step free the memory occupied by and is used to merge the root lists of and step if head[hnullthen return into single linked list that is sorted by step set prev nullptr head[hand next sibling[ptrdegree into monotonically increasing step repeat step while next null order step if degree[ptrp degree[nextor in the algorithmsteps to merge (sibling[nextp null and the root lists of binomial heaps and degree[sibling[next]degree[ptr])then into single root list in such way that set prev ptrptr next else if val[ptrps val[next]then and are sorted strictly by increasing set sibling[ptrsibling[nextdegree merge_binomial-heap(returns link_binomial-tree(nextptrroot list that is sorted by monotonically else increasing degree if there are roots if prev nullthen head[hnext in the root lists of and then merge_ else binomial-heap(runs in (mtime this sibling[prevnext procedure repeatedly examines the roots link_binomial-tree(ptrnextset ptr next at the heads of the two root lists and set next sibling[ptrappends the root with the lower degree step return to the output root listwhile removing it from its input root list step of the algorithm checks if there figure algorithm to unite two binomial heaps is at least one root in the heap the algorithm proceeds only if has at least one root in step we initialize three pointersptr which points to the root that is currently being examinedprev which points to the root preceding ptr on the root listand next which points to the root following ptr on the root list in step we have while loop in which at each iterationwe decide whether to link ptr to next or next to ptr depending on their degrees and possibly the degree of sibling[nextin step we check for two conditions firstif degree[ptrp degree[next]that iswhen ptr is the root of bi tree and next is the root of bj tree for some ithen ptr and next are not linked to each otherbut we move the pointers one position further down the list secondwe check if ptr is the first of three roots of equal degreethat isunion_binomial-heap( degree[ptrdegree[nextdegree[sibling[next]in this case alsowe just move the pointers one position further down the list by writing prev ptrptr next howeverif the above if conditions do not satisfythen the case that pops up is that ptr is the first of two roots of equal degreethat isdegree[ptrdegree[nextp degree[sibling[next]in this casewe link either ptr with next or next with ptr depending on whichever has the smaller key of coursethe node with the smaller key will be the root after the two nodes are linked the running time of union_binomial-heap(can be given as ( og )where is the total number of nodes in binomial heaps and if contains nodes and contains nodesthen contains at most og( roots and contains at most og( rootsso contains at most ( og og ps ( og ( og nroots when we call merge_binomial-heap(sincen the merge_binomial-heap(takes (log nto execute each iteration of the while loop takes ( timeand because there are at most ( og og iterationsthe total time is thus (log |
24,589 | heaps example unite the binomial heaps given below solution head [ head [ figure (aafter merge_binomial-heap()the resultant heap can be given as followshead [hptr next (step figure (blink next to ptrmaking ptr the parent of the node pointed by next head [hptr next (step figure (cnow ptr is the first of the three roots of equal degreethat isdegree[ptrdegree[nextdegree[sibling[next]thereforemove the pointers one position further down the list by writing prev ptrptr nextand next sibling[ptrhead [hprev ptr next (step figure ( |
24,590 | data structures using link ptr to nextmaking next the parent of the node pointed by ptr prev head [hptr next figure (elink next to ptrmaking ptr the parent of the node pointed by next prev ptr head [ (step next figure (fbinomial heap insert_binomial-heap(hxstep set hcreate_binomial-heap(step set parent[xnullchild[xnull and sibling[xnulldegree[xnull step set head[ ' step set head[hunion_binomial-heap(hh'step end figure algorithm to insert new element in binomial heap min-extract_binomial heap (hstep find the root having minimum value in the root list of step remove from the root list of step set hccreate_binomial-heap(step reverse the order of ' children thereby forming linked list step set head[hc/to point to the head of the resulting list step set union_binomial-heap(hhc/figure algorithm to extract the node with minimum key from binomial heap inserting new node the insert_binomial-heap(procedure is used to insert node into the binomial heap the pre-condition of this procedure is that has already been allocated space and val[xhas already been filled in the algorithm shown in fig simply makes binomial heap hcin ( time hccontains just one node which is finallythe algorithm unites hcwith the -node binomial heap in (log ntime note that the memory occupied by hcis freed in the union_binomialheap(hhc/procedure extracting the node with minimum key the algorithm to extract the node with minimum key from binomial heap is shown in fig the min-extract_binomial-heap procedure accepts heap as parameter and returns pointer to the extracted node in the first stepit finds root node with the minimum value and removes it from the |
24,591 | root list of thenthe order of ' children is reversed and they are all added to the root list of hcfinallyunion_binomial-heap (hhc/is called to unite the two heaps and is returned the algorithm min-extract_binomial-heap(runs in (log ntimewhere is the number of nodes in example extract the node with the minimum value from the given binomial heap head [ solution head [ (step head [ head [ ' (step head [ (step figure binomial heap binomial-heap_decrease_val(hxkstep if val[xkthen print errorstep set val[xk step set ptr and par parent[ptrstep repeat while par null and val[ptrval[parstep swap val[ptr]val[parstep set ptr par and par parent [ptr[end of loopstep end figure algorithm to decrease the value of node in binomial heap decreasing the value of node the algorithm to decrease the value of node in binomial heap is given in fig in the algorithmthe value of the node is overwritten with new value kwhich is less than the current value of the node in the algorithmwe first ensure that the new value is not greater than the current value and then assign the new value to the node |
24,592 | data structures using we then go up the tree with ptr initially pointing to node in each iteration of the while loopval[ptris compared with the value of its parent par howeverif either ptr is the root or key[ptr>key[par]then the binomial tree is heap-ordered otherwisenode ptr violates heap-orderingso its key is exchanged with that of its parent we set ptr par and par parent[ptrto move up one level in the tree and continue the process the binomial-heap_decrease_val procedure takes (log ntime as the maximum depth of node is log nso the while loop will iterate at most log times deleting node binomial-heap_delete-node(hxonce we have understood the binomial-heap_ decrease_val procedureit becomes easy to delete step binomial-heap_decrease_val(hx-* node ' value from the binomial heap in step min-extract_binomial-heap(ho(log ntime to start with the algorithmwe set step end the value of to assuming that there is no node in the heap that has value less than *the figure algorithm to delete node from algorithm to delete node from binomial heap bionomial heap can be given as shown in fig the binomial-heap_delete-node procedure sets the value of to *which is unique minimum value in the entire binomial heap the binomial-heap_decrease_val algorithm bubbles this key upto root and then this root is removed from the heap by making call to the min-extract_binomialheap procedure the binomial-heap_delete-node procedure takes (log ntime example solution delete the node with the value from the binomial heap (step par ptr - head [ (step (step ptr - par ptr - head [ ptr - par head [ (step head [hhead [ head [ (step - (contd |
24,593 | head [ (step head [hc/ head [ (step head [ (step figure (contdbinomial heap fibonacci heaps in the last sectionwe have seen that binomial heaps support operations such as insertextractminimumdecrease-valuedeleteand union in (log nworst-case time in this sectionwe will discuss fibonacci heaps which support the same operations but have the advantage that operations that do not involve deleting an element run in ( amortized time sotheoreticallyfibonacci heaps are especially desirable when the number of extract-minimum and delete operations is small relative to the number of other operations performed this situation arises in many applicationswhere algorithms for graph problems may call the decrease-value once per edge howeverthe programming complexity of fibonacci heaps makes them less desirable to use fibonacci heap is collection of trees it is loosely based on binomial heaps if neither the decrease-value nor the delete operation is performedeach tree in the heap is like binomial tree fibonacci heaps differ from binomial heaps as they have more relaxed structureallowing improved asymptotic time bounds structure of fibonacci heaps although fibonacci heap is collection of heap-ordered treesthe trees in fibonacci heap are not constrained to be binomial trees that iswhile the trees in binomial heap are orderedthose within fibonacci heaps are rooted but unordered look at the fibonacci heap given in fig the figure shows that each node in the fibonacci heap contains the following pointersa pointer to its parentand pointer to any one of its children note that the children of each node are linked together in min[ha circular doubly linked list which is known as the child list of that node each child in child list contains pointers to its left and right siblings if node is the only child of its parentthen left[xright[xx (refer fig circular doubly linked lists provide an added advantage as they allow node to be removed in ( time alsogiven two circular doubly linked liststhe lists can be concatenated figure fibonacci heap to form one list in ( time |
24,594 | data structures using apart from this informationevery node will store two other fields firstthe number of children in the child list of node is stored in degree[xseconda boolean value mark[xindicates whether node has lost child since the last time was made the child of another node of coursethe newly created nodes are unmarked alsowhen the node is made the child of another nodeit becomes unmarked fibonacci heap is generally accessed by pointer called min[hwhich points to the root that has minimum value if the fibonacci heap is emptythen min[hnull as seen in fig roots of all the trees in fibonacci heap are linked together using their left and right pointers into circular doubly linked list called the root list of the fibonacci heap also note that the order of the trees within root list is arbitrary min[ figure linked representation of the fibonacci heap shown in fig in fibonacci heap hthe number of nodes in is stored in [hand the degree of nodes is stored in (noperations on fibonacci heaps in this sectionwe will discuss the operations that can be implemented on fibonacci heaps if we perform operations such as create-heapinsertfind extract-minimumand unionthen each fibonacci heap is simply collection of unordered binomial trees an unordered binomial tree consists of single nodeand an unordered binomial tree ui consists of two unordered binomial trees ui- for which the root of one is made into child of the root of another all the properties of binomial tree also hold for unordered binomial trees but for an unordered binomial tree uithe root has degree iwhich is greater than that of any other node the children of the root are roots of sub-trees ui- in some order thusif an -node fibonacci heap is collection of unordered binomial treesthen (nlog the underlying principle of operations on fibonacci heaps is to delay the work as long as possible creating new fibonacci heap to create an empty fibonacci heapthe create_fib-heap procedure allocates and returns the fibonacci heap object hwhere [ and min[hnull the amortized cost of create_fib-heap is equal to ( inserting new node the algorithm to insert new node in an already existing fibonacci heap is shown in fig in steps and we first initialize the structural fields of node xmaking it its own circular doubly linked list step adds to the root list of in ( actual time nowx becomes an unordered binomial tree in the fibonacci heap in step the pointer to the minimum node of fibonacci heap is updated finallywe increment the number of nodes in to reflect the addition of the new node |
24,595 | note that unlike the insert operation in the case of binomial heapwhen we insert node in fibonacci heapno attempt is made to consolidate the trees within the fibonacci heap soeven if consecutive insert operations are performedthen single-node trees are added to the root list insert_fib-heap(hxstep [initializationset degree[xparent[xnullchild[xnullmark[xfalse step set left[xx and right[xx step concatenate the root list containing with the root list of step if min[hnull or val[xval[min[ ]]then set min[hx [end of ifstep set [hn[ ] step end figure algorithm to insert new node in fibonacci heap example insert node in the fibonacci heap given below min[ solution min[ figure fibonacci heap finding the node with minimum key fibonacci heaps maintain pointer min[hthat points to the root having the minimum value thereforefinding the minimum node is straightforward task that can be performed union_fib-heap( in just ( time step create_fib-heap(step set min[hmin[ step concatenate root list of with that of step if (min[ nullor (min[ !null and min[ min[ ])then set min[hmin[ [end of ifstep set [hn[ [ step free and step return figure algorithm to unite two fibonacci heaps uniting two fibonacci heaps the algorithm given in fig unites two fibonacci heaps and in the algorithmwe first concatenate the root lists of and into new root list thenthe minimum node of is set and the total number of nodes in is updated finallythe memory occupied by and is freed and the resultant heap is returned |
24,596 | data structures using extracting the node with minimum key the process of extracting the node with minimum value from fibonacci heap is the most complicated operation of all the operations that we have discussed so far till nowwe had been delaying the work of consolidating the treesbut in this operationwe will finally implement the consolidation process the algorithm to extract the node with minimum value is given in fig in the extract-min_fib-heap algorithmwe first make root out of each of the minimum node' children and then remove the minimum node from the root list of finallythe root list of the resultant fibonacci heap is consolidated by linking the roots of equal degree until at most one root remains of each degree note that in step we save pointer to the minimum nodethis pointer is returned at the end howeverif nullthen the heap is already empty otherwisethe node is deleted from by making all its children the roots of and then removing from the root list (as extract-min_fib-heap(hdone in step if right[ ]then is the step set min[honly node on the root listso now is empty step if !nullthen howeverif !right[ ]then we set the for each child ptr of add ptr to the root list of and pointer min[hto the node whose address is parent[ptrnull stored in the right field of remove from the root list of [end of ifstep if right[ ]then set min[hnull else set min[hright[xconsolidate( [end of ifstep set [hn[ step return figure algorithm to extract the node with minimum key consolidate(hstep repeat for = to ( [ ])set [inull step repeat steps to for each node in the root list of step set ptr step set deg degree[ptrstep repeat steps to while [deg!null step set temp [degstep if val[ptrval[temp]then step exchange ptr and temp step link_fib-heap(htempptrstep set [degnull step set deg deg step set [degptr step set min[hnull step repeat for to ( ( ]step if [ !nullthen step add [ito the root list of step if min[hnull or val[ [ ]val[min[ ]]then step set min[ha[istep end figure algorithm to consolidate fibonacci heap consolidating heap fibonacci heap is consolidated to reduce the number of trees in the heap while consolidating the root list of hthe following steps are repeatedly executed until every root in the root list has distinct degree value find two roots and in the root list that has the same degree and where val[xps val[ylink to that isremove from the root list of and make it child of this operation is actually done in the link_fib-heap procedure finallydegree[xis incremented and the mark on yif anyis cleared in the consolidate algorithm shown in fig we have used an auxiliary array [ ( [ ])]such that if [ixthen is currently node in the root list of and degree[ ] in step we set every entry in the array to null when step is overwe get tree that is rooted at some node initiallythe array entry [degree[ ]is set to point to in the for loopeach root node in is examined in each iteration of the while loopa[dpoints to some root temp because degree[ptrdegree[temp]so these two |
24,597 | nodes must be linked with each other of coursethe node with the smaller key becomes the parent of the other as result of the link operation and step remove node from the root list of step make the parent of so if need ariseswe exchange the pointers to ptr step increment the degree of and temp step set mark[yfalse nextwe link temp to ptr using the link_fibstep end heap procedure the link_fib-heap procedure (fig increments the degree of but leaves figure algorithm to link two fibonacci heaps the degree of unchanged since node is no longer rootthe pointer to it in array is removed in step note that the value of degree of is incremented in the link_fib-heap procedureso step restores the value of degree[xthe while loop is repeated until [dnullthat is until no other root with the same degree as exists in the root list of link_fib-heap (hxyexample remove the minimum node from the fibonacci heap given below min[ min[ (step temp ptr temp ptr temp (step (step temp temp ptr ptr ptr ptr ptr temp temp (step (step (step (step min[ fibonacci heap (step ptr figure (step (step (step ptr (step ptr ptr (step temp |
24,598 | data structures using decreasing the value of node the algorithm to decrease the value of node in step if val[ptro( amortized time is given in fig print "errorin the decrease-val_fib-heap (fig )we [end of ifstep set val[ptrv first ensure that the new value is not greater than step set par parent[ptrthe current value of the node and then assign step if par !null and val[ptrval[parthe new value to ptr if either the ptr points to cut (hptrparcascading-cut(hparroot node or if val[ptr>val[par]where par [end of ifis ptr' parentthen no structural changes need step if val[ptrval[min[ ]to be done this condition is checked in step set min[hptr [end of ifhoweverif the if condition in step evaluates step end to false valuethen the heap order has been violated and series of changes may occur firstfigure algorithm to decrease the value of node we call the cut procedure to disconnect (or cutany link between ptr and its parthereby making ptr root if ptr is node that has undergone the following historythen the importance of the mark field can be understood as followscase ptr was root node case then ptr was linked to another node case the two children of ptr were removed by the cut procedure note that when ptr will lose its second childit will be cut from its parent to form new root mark[ptris set to true when cases and occur and ptr has lost one of its child by the cut operation the cut procedurethereforeclears mark[ptrin step of the cut procedure howeverif ptr is the second child cut from its parent par (since the time that par was linked to another node)then cascading-cut operation is performed on par if par is rootthen the if cut(hptrparcondition in step of cascading-cut causes the step remove ptr from the child list of par procedure to just return if par is unmarkedthen step set degree[pardegree[par it is marked as it indicates that its first child has step add ptr to the root list of just been cutand the procedure returns otherwisestep set parent[ptrnull step set mark[ptrfalse if par is markedthen it means that par has now step end lost its second child thereforeptr is cut and cascading-cut is recursively called on par' parent figure algorithm to perform cut procedure the cascading-cut procedure is called recursively up the tree until either root or an unmarked node cascading-cut (hptris found once we are done with the cut (fig and step set par parent[ptrstep if par !null the cascading-cut (fig operationsstep of if mark[ptrfalse the decrease-val_fib-heap finishes up by updating set mark[ptrtrue min[helse cut (hptrparnote that the amortized cost of decrease-val_fibcascading-cut(hparheap is ( the actual cost of decrease-val_fib[end of ifheap is ( time plus the time required to perform step end the cascading cuts if cascading-cut procedure is recursively called timesthen each call of figure algorithm to perform cascade decrease-val_fib-heap (hptrv |
24,599 | cascading-cut takes ( time exclusive of recursive calls thereforethe actual cost of decreaseval_fib-heap including all recursive calls is (cexample decrease the value of node to in the fibonacci heap given below solution min[ min[ min[ (step (step (step (step (step figure min[ min[ min[ fibonacci heap deleting node node from fibonacci heap can be very easily deleted in ( ( )amortized time the procedure to delete node is given in fig del_fib-heap (hxdel_fib-heap assigns minimum value to the node is then removed from the fibonacci heap by step decrease-val_fib-heap(hx-*step extract-min_fib-heap(hmaking call to the extract-min_fib-heap procedure step end the amortized time of the delete procedure is the sum of the ( amortized time of decrease-val_fib-heap and figure algorithm to delete node from fibonacci heap the ( ( )amortized time of extract-min_fib-heap comparison of binarybinomialand fibonacci heaps table makes comparison of the operations that are commonly performed on heaps table comparison of binarybinomialand fibonacci heaps operation description create heap find min delete min insert decrease value union creates an empty heap finds the node with minimum value deletes the node with minimum value inserts new node in the heap decreases the value of node unites two heaps into one time complexity in big notation binary (no( (log no(log no(log no(nbinomial (no(log no(log no(log no(log no(log nfibonacci (no(no(log no( ( ( applications of heaps heaps are preferred for applications that includeheap sort it is one of the best sorting methods that has no quadratic worst-case scenarios heap sort algorithm is discussed in |
Subsets and Splits