0% found this document useful (0 votes)
11 views23 pages

Tree

Notes book

Uploaded by

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

Tree

Notes book

Uploaded by

nextbolt4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 23
7 | TREE Now we will discuss the concept of trees Trees are very flexible, versatile and powerful data-structures that can be used to represent data items processing hierarchical relationship betwoen the grandfather and his descendents and in turn their descendants and so on. In this chapter we will discuss the following topics «Tree (Definition), Binary Trees, . Binary Tree Representation « Trees and their applications 7.1 TREE A tree is a non-linear data structure in which items are arranged in a sorted sequence © It is used to represent hierarchical relationship existing amongest several data items. Definition : It is a finite set of one or more data items (nodes) such that A. There is a special data item called the root of the tree. B. And its remaining data items are partitioned into number of mutually exclusive (ie., disjoint) subsets, each of which is itself a tree. And they are called subtrees. The following structure shows a tree Level 0 Level 1 Level 2 Level 3 « Natural trees grow upwards from the ground into the air. But tree data structure grows downwards from top to bottom. © It is an universally practical convention for trees. (141) 142i Data Structure Using ‘C’ 7.2 TREE TERMINOLOGY ‘There are number of terms associated with the trees which are listed below = Root Node Degree of a Node Degree of a Tree Terminal node(s) Non-terminal node(s) Siblings Level Edge Path Depth « Forest Root : It is specially designed data items in a tree. It is a first in the hierarchical arrangement of data items. In the above tree, A is a root item. Node : Each data item in a tree is called a node. It is the basic structure in a tree. It specifies the data information and links (branches) to other data items. There are 13 Nodes in the above tree. Degree of a Node : It is the no. of subtrees of a node in a given tree. In the above tree : © The degree of Node A is 3 @ The degree of Node C is 1. © The degree of Node B is 2. @ The degree of Node H is 0. e The degree of Node I is 3. Degree of a Tree : It is the maximum degree of nodes in a given tree. In the above tree the node A and node I has the maximum degree 3. So the degree of the above tree is 3. ‘Terminal Node (s) : A node with degree zero is called a terminal node or a leaf node. In the above tree, there are 7 terminal nodes E, J, G, H, K, L and M. Non-terminal Node (s) : Any node (Except the root node) whose degree is not zero is called non-terminal node. Non-terminal nodes are the intermediate nodes in traversing the given tree from its root node to the terminal nodes (leaves). There are 5 non-terminal nodes. Siblings : The children nodes of a given parent node are called siblings. They are also called brothers. « E and F are siblings of parent node B. « K, Land M are siblings of parent node I Level : The entire tree structure is levelled in such a way that the root node is always at level 0. ¢ Then its immediate children are at level 1 and their immediate children are at level 2 and so on upto the terminal nodes. In general, if a node is at level n, then its children will be at level (n+1). full Ceheok » cmhlE = Edge : It is a connecting line of two nodes i.e., the line drawn from one node to another node is called an edge. Path : It is a sequence of consecutive edges from the source node to the destination node. In the above tree the path between A and J is given by the node pairs. (A,B), (BF) and (Fd). 7.3 COMPLETE BINARY TREE A Binary tree with n nodes and of depth d is a Strictly Binary Tree all of these terminal nodes are at level d. There is exactly one node at level 0, 2 node at level 1 and four nodes at level 2 and so on. Complete Binary Tree of depth 4 A Complete Binary Tree with depth 4 and level 3 You can easily verify the no. of nodes each level of a complete binary tree. For example, at level 3 there will be (2)° = 8 nodes and that nodes are H, I, J, K, L, M, N,0. 7.4 EXTENDED BINARY TREE OR 2-TREE A Binary Tree (T) is said to be a 2 Tree or an extended binary tree if each node n has either 0 or 2 children. « In such a case, the nodes with 2 children are called internal nodes and the nodes with 0 children are called external Nodes. Sometimes the nodes are distinguished in diagrams by using circles for internal nodes and squares for external nodes. How to convert a Binary Tree into Extended or 2 Tree Nyope dee EE Data Structure Using ‘C’ Example of Binary Tree SEN Example of Extended or 2 Tree : 7.5 BINARY TREE REPRESENTATION 7.5.1 Array Representation of Binary Tree « An array can be used to store the nodes of a binary tree. © The nodes are accessible sequentially. InC language, arrays start with index 0 to (maxsize — 1). The Root Node is always at index 0. Then the successive memory locations left child and right child are stored. Consider the Binary Tree with only three nodes as shown below. Let BT denote a Binary ‘Tree. 0 A) 1 2 ® © ‘The array representation of Binary Tree is as follows : BI(O) =A BI) =B BT(2)=C BI [=o A B [-1 c }—2 = If thle tree is as follows : The array representation of this Binary Tree is as follows : BT oj} A 1| 8B 2 Cc 3|-D 4, £ 51 F 6G How to identify the father, the left child and the right child = 7 Father(n) : The father of node having index (n) is at floor ((n — 1/2) if n is not equal to 0. Ifn = 0 then it is the root node and has no father. Example, consider the node number 3 > D father of D is = floor ((n ~ 1/2) = floor ((B ~ 12) = floor (1) =1 +B ‘® Ichild(n) : The left child of node numbered n is at (2n+1). For example in the above Binary Tree. Lehild(A) = /ehild(0) = 2x0+1=1 the node with index 1ie., B. © rchild(n) : The right child of node numbered n is index (2n + 2). For example in the above binary tree. rehild(A) = rehild(0) = (2n + 2) = 2(0) + 2 =2 50 Siblings If the left child at index n is given then its right sibling (or brother) is at (x + 1) and similarly if the right child at index n is given then its left sibling is at (n - 1). « The array representation is more ideal for the Complete Binary Trees. But it is not suitable for other than Complete Binary Tree as it results in unnecessary wastage of memory space. [146 a Structure Using insider the following Binary Tree It is a skewed Binary Tree. Since only the left sub tr i i tree is called left skewed binary tree ia eee aaa The Array Representation of this binary tree is as follows Br Pye 1 Br. ofa tio - 21.8 3, — 4[_— 5t 6Lc Memory wastage is there. So we used the concept of Dynamic memory allocation. 7.5.2 Linked List Representation of a Binary Tree Binary Trees can be represented with the help of linked list. This is represented with the help of following structure struct node char data; struct node *Ichild; struct node *rehil | *Root = Null; 7.6 OPERATIONS ON BINARY TREE Ichild | data | rchild Zo Ichild | data | rchild ~ Ichild | data | rehild = The basic operations to be performed on a binary tree are listed below : S.No. Operation Description 1 Create It creates an empty Binary Tree. 2. Make BT It creates a new Binary Tree having a single node with data field set to same value. 3. Empty BT It returns true if the Binary Tree is empty otherwise it returns false. 4. Lehild It returns a pointer to the left child of the node. If the node has no left child, it returns the Null pointer. 5. Rehild It returns a pointer to the right child of the node. If the node has no right child it returns a Null pointer. 6. Father It returns a pointer to the father of the node. Otherwise returns the Null pointer. 7 Brother (siblings) | It returns the pointer to the brother of the node, Otherwise returns the Null pointer. 8. Data It returns the contents of the node. Apart from these primitive operations, other operations that can be applied to the Binary ‘Tree are : se eeee ‘Tree Traversal. Insertion of Nodes. Deletion of Nodes. Searching for the Node. Copying the Binary ‘Iree. Extra operations B ~~ Data Structure Using ‘C’ 7.7 TRAVERSAL OF A BINARY TREE Tree travesal is one of the most common operations performed on tr structures. ee « It is a way in which each node in the tree is visited exactly once in a sy manner. te, e There are many applications that essentially require traversal of Binary Trees, elon example, a Binary Tree could be used to represent an arithmetic expression 28 shy @® © ¢ The Full Binary Tree Traversal would produce a linear order for the nodes it Binary Tree , « There are three popular ways of Binary Tree Traversal. They are : e Preorder Traversal e Inorder Traversal e Postorder Traversal 7.7.1 Recursive Traversal (a) Inorder traversal L.N.R. The Inorder Traversal of a non-empty binary tree is defined as follows : 1. Traverse the left subtree in Inorder (L) 2. Visit the Root Node (N) 3. Traverse the right subtree in Inorder (R). ‘That is, in an Inorder Traversal, the left subtree is traversed recursively in inorder visiting the Root Node. « After visiting the Root Node, recursively again in inorder. the right subtree is taken up and it is tr For example, ‘The Inorder Traversal is as follows : DBEAFCG ‘The function in C for an inorder Traversal is as follows : Void inorder(struct node*p) if (p != NULL) inorder(p + left); printf(“\n%d", p + num); inorder(p —> right); } (b) Preorder traversal « The preorder traversal of a non-empty binary tree is defined as follows = NLR 1. Visit the Root Node 2. Traverse the left subtree in preorder(L), 3. Traverse the right subtree in preorder(R). A nae For example, aoe ‘ am [~ 2 Ea * A FY J K € / u ——— NLR A BDEL cFGJ | ttt—+ +t | LSE The funciton in C language is as follows Void preorder (struct node*p) t if (p != NULL) printf(*\n %d”, p — into); preorder(p — left); preorder(p — right); r Ey Structure Using C’ (0) Post order traversal LRN ‘The Post Order Traversal of non-empty binary tree is defined as follows : 1. Traverse the left subtree in Postorder(L). 2. Traverse the right subtree in Postorder(R). 3. Visit the Root Node(N). 4 he ‘The function in C language for postorder traversal is as follows : Void postorder (struct node*p) ( he: if (tree != NULL) \ postorder(p > left); postorder(p - > right); printf(*\n%d”, p —} num); ' ! \ Problem : Write aC’ program for the following menu + t Create lemo} In order Lin Preorder Postorder 5. Exit Enter your choice Solution : #includecstdio.h> #include #include fincludecstdlib.h> struct node { int num; struct node “left, *right; } *Root = NULL; struct node*insert(struct node *, int); Void preorder(struet node"); Void postorder(struct node*); Void inorder(struct node"); int count = 1; Void main() int ch, n; char chl; do printft“\n 1» Create”); printf(“\n 2 » Inorder Traversal”); printf“\n 3 Preorder Traversal”); printft“\n 4 > Postorder Traversal”); printft“\n 5 > Exit”); printf(“\n Enter your choice”); scanfi“%d", &ch); switch(ch) { ease 1 : printf(“\n Enter the value which you want to insert”); scanf(“%d", &n); root = insert(root, n); break; case 2: printf“\n The inorder Traversal is”); inorder (root); break; case 8 : preorder (root); break; case 4 : postorder (root); break; case 5: exit( 1); | printf(*\n Do you want to continue ( Y/N)"; fflush(stdin); scanit"%c”, & ch); EE Data Structure Using 'C’ | while(chi getch(); ‘'y UU chi = ot); ' struct node*insert(struct node *p, int digit) if (P == NULL) P = (struct node*) malloc (size of (struct node)); P left =P right = NULL; p > num = digit; count ++; else if (count % 2 == 0) P - left = insert (p -> left, digit); else P -» right = insert(p > right, digit); return(P); Void preorder(struct node*p) if (p != NULL) printft"\n %d”, p -» num); preorder(p -» left); preorder(p -» right); ' ‘ ! Void inorder(struct node *p) { if (p != NULL) inorder (p — left); printf“\n %d”, p > num); inorder(p -> rights Void postorder(struct node*p) if (p != NULL) postorder (p — left); postorder (p > right); printf“\n Sed”, p -> num); | Tee 7.7.2 Non-Recursive Traversal The Binary ‘Tree is also Traversed in non-recursive way using stack. (a) Preorder traversal « This also traverses the tree in preorder non-recursively using stack. « Initially push Null onto stack and thus set P = Root. Then repeat the following steps input. (P |= NULL) Step 1: Proceed down the,left most path rooted at P, processing each node N on the path and pushing each right child P — right onto stack. The traversing ends after a node N with no left child L(N) is processed ‘e Therefore, the pointer P is updated using the assignment P = P - left and the traversing stops when P — left = Null ‘« Pop the element from stack and assign to P, If P # Null then return step 1, else exit. (b) Inorder traversal « This also traverses the tree non-recursively in Inorder using stack. « Initially push Null onto the stack and then set P = Root and repeat the following steps until Null is popped from stack. Step 1: Proceed down the left most path rooted at P, pushing each Node N onto stack and stopping when a Node N with no left child is pushed onto stack. Step 2 : Pop and process the nodes on stack. If NULL is popped then exit. Ifa Node N with a right child P + right is processed set P = P — right and return to step 1 « Preorder Traversal iterative (root) Here Root is a Pointer variable that holds the address of root node of the given tree. It use a stack s whose elements are pointers to type BST. It uses a temporary pointer variable ptr to hold the address of Current Node. Begin CreateEmptystack(s) push(s, Null) set Ptr = Root while (Ptr != Null) do Print : Ptr -> info iffPtr - left != Null) then set Ptr = Ptr left; else if (Ptr — right # Null) then set Ptr = Ptr — right else set Ptr = Pop(s); end if end while end El Data Structure Using ‘C’ InorderTraversaliterative(root) Begin Createemptystack(s) push(s, Null) set Ptr = root set done = false while (not done) do while (ptr != Null) do push(s, ptr) set Ptr = ptr -> left end while set Ptr = pop(s) set flag = true while (ptr # Null and flag == true) do print Ptr — info if (Ptr > right #Null) then set ptr = ptr — right set flag = false atari SAREE RTM Ao era eee else set ptr = pop(s) end if end while if (ptr = Null) then set done = true end if end while end {0 Post order traversal In the Post order traversal we consider the LRN ie., Left, Right, Node Then the logic is as follows : Firstly we traverse the tree with the help of iteration and push the Nodes in the order LRN and when the elements are pushed into the stack then we have to pop the elements in the form of Left, Right and Node. The algo is same except, the case, firstly we have to traversal the left child, then we have Thee ‘to traverse the right child and then we print the node. my 7,8 CONVERSION OF AN EXPRESSION INTO BINARY TREE ‘e Divide and conquer technique is used to convert an expression into a Binary Tree. i ¢ Note the order of precedence. All expressions in parenthesis are to be evaluated first. ‘¢ Exponential will come next Tee FEB « Division and multiplication will be the next in order of precedence. « Subtraction and addition will be the last to be processed, Examples : . A+(B+C*D+B)+h/G In the above example the parenthesis expression will be evaluated and added to the left expression. Go on dividing the expression as follows till you get element operand. A+(B+C*D+B) FG Le A (BGxD4B) FF G (B+C*D) B B CD) c D Join all the elementary operands with the operators. The result will be shown as follows : avian es © © Preorder « ««AB«CD Postorder es ABCDs + . As Bees Dei BaP. = SoS . (AcB) && (BEC) BH (CKD! 7.9 PROPERTY OF BINARY TREE Troe has one very interesting property —- property is that if we are given in order tear ad tha of preorder oprah, w incnatrect the Binary Tre Tree Problem : Consider that a Binary Tree has 8 nodes. The Preorder and Inorder traversals * of binary tree T yield the following sequence of nodes Preorder: A BDEGH CF Inorder: D BG EH ACR ee Draw the Binary Tree T. Solution : The Binary tree T is drawn as follows ‘The first node in the preorder traversal is always a root node of the Binary Tree. Thus, the root node of the Binary Tree T is node A After determining the root node of the Binary ‘Tree, our aim is to find the nodes that comprise the left subtree and right subtree of node A. + Wo know from the inorder traversal that first left subtree is traversed then root node and finally the right subtree, ‘Thus, all the nodes to the left af node A in inorder traversal comprise its left subtree, Similarly all the nodes to the right of node A in inorder traversal comprise its right subtree pecen} (@) cr Inorder {Le subtree Ly) Root [Right subtree Ral So the Partial Binary Tree is constructed so f In the same way, we can construct the left subtree Ly, and right subtree Rry Lotus first consider the left subtree Lng. ‘The Preorder and Inorder traversal sequences of the left subtree Liyq are : Preorder —BDEGH Inorder —D BG EH ‘The above Procedure partitions the preorder and inorder sequences as shown below : Inorder (1 | GEH Left subtree Root Right subtree Preorder (8) [D | EGH Root Left subtree —_Right subtree Data Structure Using ‘C’ Now Preorder —EGH Inorder —GEH Inorder ¢] @ @ Left subtree Root Right subtree Preorder (8) [e] H Root Left subtree Right subtree Preorder — CF Inorder — CF Preorder Tnorder © F Root Left subtree Right subtree Left subtree © Root F Right subtree 7.10 HUFFMAN’S ALGO Recall that an extended Binary Tree or 2 Tree is a Binary Tree T in which each node has either 0 or 2 children. The Nodes with 0 chilren are called external Nodes and the Nodes with 2 children are called internal Nodes. In any 2 Tree, the number of External Nodes Ng is one more than the number of Internal Nodes (N,) Ne=Niv For example : In this figure The number of External nodes = 7 Number of Internal nodes = 6 rR * Frequently an algo can be represented by a 2 Tree T where the Internal Nodes represents tests and the External Nodes represents actions. © With this in Mind, we define the External Path Length Ly of a 2 Tree T to be the sum of all Path lengths summed over each path 2 from the Root R of 1 to an external node of the above figure. Lg> 2424344444343 = 21 = 04+1414+24+2+3 =9 Observe that Ineo, = 9+2%6=9412=2=Lp where n is number of internal nodes. Formula where n is the number of Internal Nodes Is true for any 2 tree with n internal nodes. Suppose T is a 2 tree with n external Nodes and suppose, each of the external nodes is assigned, a (non negative) weight. The external weighted Path length P of the Tree T is defined to be the sum of the weighted Path Lengths. ie, P = WL, + Wale + Wyby +... + Waly, where W, and L; denote respectively, the weight and path length of an external Node Nz. FEE) _ Date Structure Using 'c" | « Consider now the collection of all 2 Trees with n external nodes. Clearly the complete Tree among them will have a Minimum External Path Length Ly For example : If we have the following ‘Iree 2 Trees, © a ‘The weighted path lengths of these trees are as follows : Pp= 2x2+3x2+5x2+i1x2 = 44+6410+22=42 Po= 2x1+1Lx2+3x3+5x3 = 2+22+9+15=48 Pye 1Lx1+5x%24+2x34+3x3 = 114104+6+9=36 P, and P; indicates that the complete tree need not give a Minimum Path Length P and the quantities p, and Py indicate 4 that. Similar trees need not give the same length. « The general problem that we want to solve is as follows : Suppose a list of n weights is given Wy, Woy Wy) ones Wy ‘Among all the 2 trees with n external nodes and with the given n weights, find a tree ‘T with a minimum weighted path length. (Such a tree T is seldom length). Huffman gave an algo for finding minimum weighted path length. Huffman’s Algo Suppose W, and W, are two minimum weights among the n given weights W,, Wa, Ws, .- W,. Find a tree TT” which gives a solution for the (n ~ 1) weights. Wy + Wo, Wy, Wy ‘Then in tree T’ replace the External Nodes. W, + W, by the subtree oO), wy) Then new 2 Tree T is the desired solution. Example : How To Build a Huffman Tree |—— + spi]c]pD]E| F/G] H Data Item A Weight (2G) @| Tree i 1] F c @ @) 2 PF 3 G A . 9 19 { fy) fq a F} ic {s L Ww 2 5 Ee] |B Final Huffman Tree SUMMARY ‘A tree is a Non Linear Data Structure in which items are arranged in a stored sequence. ‘Trees are used to represents the hierarchical relationship existing amongest several data items. ‘A Binary Tree is a finite set of data items which is either empty or consists of a single item called the root and two disjoint Binary Tree called the left subtree and the Right subtree. Binary Tree can be represented using either sequntial representation or linked list representation. Binary Tree can be traversed in Inorder, Preorder and Postorder. ‘The property of a Binary Tree is as follows If the Preorder/Postorder and Inorder Traversals of a Binary tree is given then we can draw the tree,

You might also like