You are on page 1of 27
sf [ntroduction we have studied about arrays, st, fal YS, Stacks, gu . 0 cues . ae data structures. These aré termed as linear as linked lists, which ete li ion. There are many applicati ions inves Decaus own as “at f in “use the elements a fineal Teal-life situati re arranged in re such as trees and gray . uations th; ma a suru raph, Here, in this chapter a ft of ton near ‘USS about trees, (8) (c) 6) © © ©OO w ® ® Figure 6.1 Tree Tees are very flexible, versatile and powerful data structures in computer science that can beused torepresent data items processing hier jonships between data elements. Figue 6.1 shows the structure of a tree. Thete are several examples where tree structure is the efficient means to maintain and Mani : nts. “pulate data. For example: records, table of contents ‘plication of Trees i stems. © Trees are used to implement the fil em of several popular operating sy: * Trees can be used to evaluate arithmeti apres , 1) averagetimes and to * Trees are used to support searchin, ; zion and how to implement worst- Tefine these ideas to obtain O(log 7. ona disk. these operations when the data are stored 62. * Data Structures Using C 6.2 Tree a ntains no loops and no ¢ ‘A traeis arvaoyelic simple, connected gra h, A tree contains no loops and no cycles. The, is no more than one edge between any pair of nodes. We can define a tree recursively. A tree is 4 collection of, codes The collection can i istingui 7, called the root, and empty. Otherwise, a tree consists of @ distinguished node r, 2et0 oF mop T, T. , each of whose Toots are connected by an edge frome non-empty subirces T. : : f each subtree is said to be a child of r, and ris the parent feach subtree roo, The root of From the recursive definition, we find that a tree is a collection of7nodes, one of which ig the root, and n-1 edges, There are 2-1 edges follows from the fact that each edge connect some node to its parent, and every node except the root has one parent. Figure 6.2 shows generic tree structure. Figure 6.2 Generic Tree 6.3 Tree Terminology There are number of terms, associated with the trees, which can be explained with the help of a tree which is shown in Figure ‘& Level Level! Level2 Level3 Figure 6.3 Tree Node: Each element ofa tree is called anode. It is the basic structure ina tree. It specifies information and links (branches) to other data items. There are 14 nodes in this tree . Tre Itis specially designated node in a tree, It is th ae 8 at: . : \e first ir i _ 8 items. In this tree, A is the root node, Btunade in the hierarchical arrangement = t of a node is the immedi rent: Paren late predecess, i re F eececess Sor of a node, Here, B is the parent of cuild: Each im r of a node is known as child. In this tree B, C, D are children of A. casings: The child nodes ofa gi siblings: NEN parent node are called siblings. inthe given tree, H,1,J are siblings. ad HI, ree of node: The number of subtrees of ina gi is at Figure 63, Seer eeS OF a NOde in a given tree is called degree of that © The degree of node A is 3. The degree of node B is 2. @ The degree of node G is |. © The degree of node F is 0. Degree of a tree: The maximum degree of nodes in a given tree is called the degree of the tree. In Figure 6.3, the maximum degree of nodes A and D is 3. So, the degree of tree is 3. Terminal node: A node with degree zero is called a terminal node or a leaf. In the tree shown in Figure 6.3, K, F, L, H, M, N, J are terminal nodes. Non-Terminal nodes: Any node (except the root node) whose degree is not zero is called non-terminal node. In the tree (shown in Figure 6.3) B, E, C, G, D, | are non-terminal nodes. Level: The entire tree structured is levelled in such a way that the root node is always at level 0. Then, its immediate childrén are at level 1, and their immediate children are at !evel 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, Here in Figure 6.3, there are Alevels, —— Edge: Edge is a connecting line of two nodes. CG.is an edge in the twee of Figure 6.3 —_——_—_—_—_— . : the source node to the destination node. Path: Path is a sequence of consecutive edges from d 8 a . Inthe tree of Figers 6.3, the path between A and M is given by node pairs, (A,D), (D,Jyand (LM). | i ith from the root ton. Th . is the length of the uni ue path from the root to m,. Thus, the mae Tie fF G3, the depth of E is 2 and depth of Bis 1. lepth 0. ~ 64 & Data Structures using C iethe length of the lon est path from.to a leaf. 7) ght of node 7,18 aht of the root Ini a al = = Tee ¢ is equal to the Height: The hei y leaves are atpeight 0, The heii a ou ‘ Figure 6.3, the height of Bis 2 and hei tof Fis 0. from n, to n,, then 7, is an ancestor of p is ith ‘Ancestor and descendant: If there is apa 1 0.7 niga descendant of n, . In the tree of Figure 6.3, A is The ancestor of G and C and K 3p 4 fescendant of B and b- 6.4 Binary Tree A binary tree is a very important and the most commonly used non-linear data structure called nodes, such that: A binary tree Tis defined as a finite set of elements, i) Tis empty (called the null tree oF empty. tree), OF ii) T contains a distinguished node R, called the root of Zand the remaining nodes, T form an ordered pair of disjoint binary trees T, and T, which are called A subtree and the right subtree respectively. < Figure 6.4 Binary Tree If 7, is non empty, then its root i : /, ot is called the le i root is called the right successor of R. A sesso oT Isr ™ In the Figure 6.4, the tree, 7 i ao. 2, Tconsists of 11 nodes represented by letter A, B, C, D, E,F.GH i) Bi: ig i) B isa left successor and C is a right successor of the node A. —__ —_—— ii) The left i) veh of ubiee ftihe root I sae of the nodes B, D, E and F and the ists of the nodes C, G, H, J, K and L. Trees#® 65 oden ina binary tree Thas either 9, |. o, 2 succe: ay the nodes E and J have only ope The nodes A B,CandH have a cessors, he nox i sor, and the n successors. des with no 5 od ve NO. $801 Ll les DG, Land Sare called termi, <——— is an ancestor of node n, (and nyisa “inal nodes descendant ofn,) ifn is either th le it of parent of some ancestor of 7, In the Figure 6.4, A is an an mds A Ais an ancestor of G, and J is a 1,0 dant of C, but E is neither an ancestor nor a descendant of C. desce ode n, isa left descendant of node n, ifn, is either the left child of n, or a descendant Fe He left child of ,. Similar for right descendant, wo nodes are siblings if they are left and right children of the same Parent, iv 64.1 Strictly Binary Tree ifevery non leaf node in a binary tree has hon empty left and ri vaand right subtrees, the tree is tamed strictly binary tree. A strictly. bina ry tree with 7 leaves always Contains 2n-1 node Figure 6.5 shows a strictly binary tree, : — Figure 6.5 Strictly Binary Tree 64.2 Level of anode in a binary tree in the tree is one more than 0, al el of any other node in t 1 i oi i eae ee tree is the maximum level of any leaf in the tree. 2 copier leaf. 7 ‘Qals the length of the longest path from the root to any 43 Complete binary tree Id. i /hose leaves are at level 1O"Plete binary tree of depth dis the strictly binary tree se teee ae i binary tree contains ™m nodes at level /, it contains at mo: ir —_=r —— lar ‘oot), it can contain at most “he abin ry tree tain at most one nodeat level 0 the root), i e can cont \ 6.6 # Data Structures Using C Level Level | Level ce Level Figure 6.6 A complete binary tree of level 3. Depth of the tree is 3 2! nodes at level /. A complete binary tree of depth d is the binary tree of depth d th contains exactly 2! nodes at each level / between 0 and d. and d. (This is equivalent to saying tha, Yee it is the binary tree of depth d that conta contains exactly ctly 2” nodes at level d.) Figure 6.6 shows complete binary tree of level 3. The total number of nodes ina complete binary tree of depth ——— d, tn, equals the sum of the number of nodes at each level between 0 and d. d Thusin =2°+2'+2?+..,.+ 2 = x2 Fi Pa Since all leaves in such a tree are at level d, the tree contains 24 leaves and, therefore, 24-1 non leaf nodes. If the number of nodes, mm, in a complete binary tree is known, we can compute its depth d, from the equation n = 2*'- 1. Ina complete binary tree, depth, d equals log, (+1) -1 If m = number of nodes = 15 (say), then = log, (15 + 1)- 1 = log, 16 - =4-1=3 d= 6.4.4 Almost complete binary tree A binary tree of depth d is an almost complete binary tree if: i) Each leaf in the tree is either at level d or at level d-1. as ii) For any node nd in the tree with a right descendant at level d, all the left descend of nd that are leaves are also at level d. @ © Figure 6.7 binary tree of Figure 6.7(a) is not almost complete, since it contains leaves at he strict ——— jyels 1,2 and 3, there by violating condition (i). The strictly binary tree of Figure 6.7(b) satisfies: condition (i), since every leaf is either at level 2 or at level 3. However, condition (ii) riolated, since A has a right descendant at level 3 (i.e. J) but also has a left descendant that isaleaf at level 2 (i.e. E). (A) (a) Gg ® on A é ) ® OU (a) (b) Figure 6.8 Thestitly binary tree of Figure 6.8(a) satisfies both conditions (i). and (ii) and is therefore uitest Complete binary tree. The binary tree of Figure 6.8(b) is also an alm complete "ary but is not strictly binary, since node E has a left child but not a righ —— ae ———— x almost complete binary tree of depth dis intermediate between the complete binary tree mt 4-1, that contains 24 - 1 nodes, and the complete binary tree of depth d, which «tains 2" 1 nodes, If m is the total number of nodes in an almost complete binary tree, its “Phisthe largest integer less than or equal to log, *. %® Data Structures Using C 6.5 Memory representation of binary tree A tree must represent a hierarchical relationship between a parent node and child p, des There are two common methods used for representing this conceptual structure, ’) Linear (or sequential) representation using an array ii) Linear list representation using a pointer 6.5.1 Array representation of binary tree This representation uses only a single linear array. tree as follows: i) The root of the tree is stored in tree(0]- ii) Ifanode occupies tree(i), then its left child is stored in eree[2*i+1], Its right child is stored in tree(2*i#2], and the parent is stored in tree[(i-1)/2]. — —_— (5) “ % @ ©) (a) Binary tree [s [4 [« |» |» 2 0 1 2 3 4 5 6 7 (b) Array representation of binary tree Figure 6.9 Binary tree and its array representation Figure 6.9 shows a binary tree and its corresponding array representation. 6.5.2 Linked representation of binary tree Anode is divided in to three fields, info Which is used to store the data item, left Left pointer field which is used to store the address of the left child. eee Whi then the corresponding pointer wil is empty, then the root will contai root 44 331x [x [so] x ek] Figure 6.10 Linked representation Figure 6.10 shows the linked representation of binary tree shown in Figure 6.9 (a). 66 Traversing a Binary Tree The process of going through a tree in such a way that each node is visited once and only once is called ¢ree traversal. When a tree is traversed, its entire collection of nodes is loked at. Several methods are used for tree traversal. Each imposes a sequen al, linear ordering upon the nodes of a tree. Thus, different orderings are used for traversal in different “cases, The traversal in a binary tree involves three kinds of basic activities such as: ( Misiting the root ( Traverse the left subtree _ Traverse the right subtree The only difference among the methods is the order in which these three operations are terformed. There are three standard ways of traversing a nonempty binary tree namely Preorder, inorder and postorder are as follows: a 6.10 * Data Structures Using C Preorder (also known as dej th-first_order) 1, Visit the root 2. Traverse the left subtree in preorder 3, Traverse the right subtree in preorder Inorder (also known as symmetric order) Sy 1. Traverse the left subtree in inorder ya 2. Visit the root 3, Traverse the right subtree in inorder Postorder 1. Traverse the left subtree in postorder 2. Traverse the right subtree in postorder 3. Visit the root Preorder : ABDHIECFIKG Inorder : HDIBEAJFKCG _ Postorder + HIDEBJKFGCA Q. Preorder : ABDHIESCEG 2 Oo © Inorder : HDIBJEAFCE (x) (NG) Postorder ; HIDJEBFGCA (b) Figure 6.11 Binary tree and their traversals Figure 6.11 illustrates the three different traversals of binary trees. ‘6 preor' ol eo thon 61 . sina tree is in memory. ie address of the root node of the tree der traversal , je holds th der (node) 1 trmode # NULL Process (node) preorder (left [node}) i Preorder (right[node}) (End of Step | If structure.] 5, Exit. 66.12 Inorder traversal Algorithm 6.2 Abinary tree is in memory. node holds the address of the root node of the tree Inorder (mode) 1. If node # NULL 2. Inorder (left [node]) 3. Process (node) 4. Inorder (right{node}) [End of Step 1 If structure.] 5. Exit, 661.3 Postorder traversal Algorithm 6,3 Abinary tree is in memory. "ode holds the address of the root node of the tree Postorder (node) ' Wnode # NULL 2 Postorder (left [mode]) . Tr 1 recursive Algorithm for Tree Traversal meee Data Structures 3. Postorder right(nodel) | Process (node) [End of step | If stu 5. Exit. ture.) Tree Traversal ursive Algor . p 6.62 Nonrecusn versal will be implemented by using stacy. Ss Non recursive procedure 6.6.2.1 Preorder Traversal Algorithm 6.4 This algorithm uses preorder traversal of the tree, A binary tree is, in memory. node of the tree. root holds the address of the root PreorderTrav (root) 1. Set top = 0, stack{0] = NULL, [Initially push NULL onto stac! teps 3 to 5 while node # NULL node = root and initialize node) 2. Repeat S 3. Process (info{node}) [ Process the node] 4. If right (node] # NULL Set fop = top + |, stack{top] = right{node] [Push the right child into the stack] [End of Step 4 If structure.) 5 If left{node] # NULL Set node = lefi{node] Else Set node = stack{top), top = top - | [ Pops node from stack] [End of Step 5 If structure.] } [End of Step 2 loop.] “9 10. Exit Example : Consider the binary tree shown in Figure 6.12, We simulate the algorithm P: reorderTrav wit i contents of stack at each step, Ss i rigure 6! Trees ® 6.13 N ode Stack ters tritially push NULL » on to stack. set node = j) Process A and push its ? right child on to stack ji) Process B (no right child exists ii) Process D and push its right child on to stack No rocessed since phas no left child 3) Pop the top element from stack and Set node = G 4) Since node # NULL Enter in to the loop process G (no right child exists) exists) No other node is processed. Since G has no left child Pai eine 5) Pop the top element from stack and Set node = C §) Since node # NULL Enter in to the loop i) Process C and push its Procesesed c ight child on to stack. top 6.14 & Data Structures Using C . ight child exists) ii) Process E (no ri ; cessed since E No other node is pro has no left child 7) Pop the top element from stack and set node = F 8) Since node # NULL Enter in to the loop. Process F (no right child exists) No other node is processed since F has no left child. 9) Pop the top element from stack Stack Empty and set node = NULL 10) Since node = NULL the algorithm is Completed. In this example the nodes are processed in the order AB DGCEF ——L, 6.6.2.2 Inorder Traversal Algorithm 6.5 ’ A binary tree is in mémory. This algorithm uses inorder traversal of the tree, root holds the address of the root node of the tree InorderTrav(root) : 1. Set top = 0, stack{0] = NULL, node = root [Initially push NULL on to stack and initialize node ] 2. Repeat while node # NULL [ Pushes left most path on to stack ] Set top = top + |, stack{top] = node Set node = left{node) [End of Step 2 loop.] 3. Set node = stack{top], top = top - | [ Pops node from stack ] ; Trees ® 6.15 4, Repeat Steps 5 to 7 while node + NULL process(info[node]) [Process the node] 6 If right{node] # NULL [right child exits] Set node = right[node}, Go to Step 2 [End of Step 6 If structure,] 7, Set node = stack{top), top = top -| [ Pops node from stack ] {End of Step 4 loop] next -" /\y ® = . ® 2 Example: Consider the binary tree shown in Figure 6.13, We simulate @ © the algorithm InorderTrav with the tree showing the contents of stack 2 at each step. Figure 6.13 Steps Node Stack Procesesed ‘ TT 1)_ Initially push NULL on to stack. Set node = A eee 2). Push node-A, B, D top D | on to stack (e| to 3) Pop D and process ( We D top LB stop at D since Dhas aright tI child) setnode = G, the-right child of D. 4) node =G, push node G top| on to stack (no other node 8 is pushed, since G has no 0 —— left child) 6.16 ¥ Data Structures Using Cc 5) PopG, B, A and process (we stop at A since A has aright child) set node = C the right child of A. elite él top| >wa 6) node =C, push node C and — top E on to stack (no other node is pushed, since E has no left child) Elolr 7) Pop E and Cand process (We |. Stop at C since C has a right child) ic top set node = F, the right child of C Ss 8) node = F, push node F onto stack top|_F 0 (no other node is pushed, since F has no left child) 9) Pop F and process (We stop at F since F has no right child) topo The next element NULL is popped. Since node = NULL the algorithm is completed Stack empty In this example the nodes are processed in the order DG B AECF \ — os 6.6.2.3 Postorder Traversal Algorithm 6.6 A binary tree is in memory.This algorithm uses postorder traversal of the tree. root holds the address of the root node of the tree. PostorderTrav(root) 1. Set top'=0, stack{0] = NULL, node = root [Initially push NULL on to stack and initialize node } 2. Repeat Steps 3 to 5 while node # NULL [ Pushes left most path on to stack ] 2 Trees ® 6.17 Set top = top + |, stack{top| = node [ Pushes node on to stack ] cle right{node] # NULL [right child exits] Set top = top + |, stack{top} = right (node}) [Pushes the negative pointer] {End of If structure. 5, Set node = left{node] [End of Step 2 loop.] 6, Set node = stack{top], top = top - | [ Pops node from stack } 7, Repeat while node > 0 [while non negative pointer) Process(info[node]) Set node = stack{top), top = top - | [End of loop.] 8. If node <0 [Test for negative pointer] Set node = -node [Change to the original value of node] Go to Step 2. [End of If structure.] 9. Exit. Example : Consider the binary tree shown in Figure 6.14. We simulate the algorithm InorderTrav with the tree showing the contents of stack at each step. Figure 6.14 6.18 # Data Structures Using C Steps 1) Initially push NULL on to stack. Set node = A 2) By taking node = A proceed to left most path, on the way if right child is obtained push-ve Of that on to stack. 3) Pop and process +ve node if-ve, node is popped make it +ve and repeat the step. - Gis popped so, node = - G Now reset node = G 4) By taking node = G proceed to left most path, push G on to stack 5) Pop and process G, D, and B. - C is popped so, node = - C now reset node = C 6) By taking node = C, proceed to left most path if right child is obtained push - ve of that on to stack.Push C - F and E 7) Pop and process E. -F is popped so, node = - F now reset node = F} Node Procesesed Stack top top Eevee el top [[a]e[2] top| of>Jaf=fefo] s g Eel Ss 3 EEE FEEL 9) Pop and process F, C and A 10) The next element NULL is popped since node = NULL * algorithm is completed. Inthis example the nodes are processed in the order GDBEFCA, inthis postorder traversal, if the left child off anode is encountered, then itis pushed into the gackas such. If the right child of the Node is‘encountered, then the negative address of that adewill be pushed into the stack to distinguish between left child and the right child, Whenever , p operation is performed and found the node value Positive (i.e. the left child which has een pushed into the stack) then it will be processed. Ifa negative pointer is popped (i.e., the right child has been pushed earlier) then it will be pushed again by changing its sign. In this case, anode will be processed only when it is popped from the stack and it is positive. 66.3 Construction of binary tree Atree can be constructed if preorder and iaorder traversal is given, an example of which is given in Figure 6.15, Figure 6.16 shows a tree if postorder and inorder traversal is given. Example: Construction of the tree ftom its given preorder and inorder traversal, Preorder: AB DEF CGHJLK Inorder : DBFEAGCLJHK GoLIHK LH K Figure 6.15 Construction of a tree from its preorder and inorder traversal 6.20 % Data Structures Using C ler traversal is the root node of the tree (in tp, aby, a 1, The first node in the preord figure it is A) ode (i.e, A) in inorder traversal. The Nodes versal are the nodes of the Jeft subtree Of th le 2. Find the position of the root n .d to the root node are the nodes i 8 intherg to root’node in the inorder tra node (i.e. DBFE. and the nodes succee subtree of the root node (i.e. GCLJHK). — Now-consider two sets of inorder and preorder traversals of the left and subtrees of the root. The first set is the nodes appear precede to the root n Tigh, inorder traversal (i.e. DBFE) and the combination of those nodes only i preorder traversal just after the root node (ie, BDEF). The second ei nodes appear after the root node in inorder traversal (i.e. GCLJHK) and the ies in the preorder traversal except the root node and the nodes considered in theg, rst set (ie. CGHJLK). |. Taking these two sets of preorder and inorder traversals for left and right subj we will repeat steps 2 and 3 till the entire tree is constructed. sa w Example: Construction of the tree from its given postorder and inorder traversal Postorder: DFEBGLJKHCA il Inorder :DBFEAGCLJHK GOLJHK Figure 6.16 Construction ofa tree from its postorder and inorder traversal he ex : tea node in the postorder traversal is the root node in the tree (in! itis 2, Find the position of the root node (i.e, A) in the above example in inorder travesal, The nodes precede to root node in the inorder traversal are the nodes in the left subtree of the root node (i.e. DBFE) and the nodes succeed to the root node are the nodes in the right subtree of the root node (i.e. GCLJHK). . Now consider two sets of inorder and we Postorder traversals of the left and right subtrees of the root. The first set is the nodes appear precede to the root node in inorder traversal (i.e. DBFE) andthe Sequence of same nodes that are in postorder traversal just before the root node (ie. DFED). The second set is the nodes appear after the root node in inorder traversal (ie. GCLJHK) and the sequence of nodes that are in the postorder traversal except the root fiode and the nodes considered in first set (42. CGHJLK) Taking these two sets of postorder and inorder traversals for left and right subtrees, we will repeat steps 2 und 3 till the entire tree is constructed, oa Example: Construction of the tree from its given preorder and postorder traversal, Preorder: @®p GHK re F > “ Postorder : G K H DBIE FO aaian ® @ QOmk Opn Bpe uni Ax@Q é & ne é Figure 6.17 Construction of a tree from its preorder and postorder traversal |. The first node in the preorder traversal and last ndde of the postorder traversal (which are same) is considered as the root node of the tree (i.e. A in the Figure 6.17). Find the succesor of the root node in preorder traversal, say, 7i1 arid predecessor of the root node in postorder traversal, say, n2. Then there will be two cases: ') Ifa = n2 then this node is considered to be the left Lor right child of the root node, — in which the construction of tree is not unique. 6.22 * Data Structures Using Gi i Ifml # n2.then Lis considered as the left child (i.e B) and y2is considereg " ath, rightohild (i.e. C)of the root node. B) in preor 3. Find the positions of 72 C) and + tay respectively. Now consider the Two sets of preorder and postorder traversal, fe ; and right subtrees of the root. The first set is the nodes appear after m1 and bef; DGHK) and the nodes precede to node 71 in re Nr in preorder traversal (7.2. traversal (i.e. GKHD), The second set is the nodes appear after 2 in preorder tray, ‘esa (ie. EF) and the nodes in between n\ and n2 in postorder traversal (ie. ER), — Taking these two sets of preorder and postorder traversals for left and right Subtregs we will repeat the steps 2/and 3 till the entire tree is constructed. 6.7 Expression Trees Figure 6.18 shows an expression tree for (a+ b*c)t(d*tetf)*g) Figure 6.18 Expression tree for (a +b *c) + ((d *e + f) *g) The leaves of an expression tree are operands, such as constants or variable names, andthe other nodes contain operators. This particular tree happens to be binary, because all oft operations are binary, and although this is the simplest case, it is possible for nodes tohavt more than two children. It is also possible for a node to have only one child, as in the o®® with the unary minus operator. We can evaluate expression tree, 7, by apply ing the opetst at the root to the values obtained recursively by evaluating the left and right subtrees, Int example, the left subtree evaluates to (a+ b * c) and the right subtree evaluates (0 qe + f) * g. The entire tree therefore represents: (at+b*c)+(d*etf)*g) inorder traversal (infix representation) atb*tctd*etf*g postorder traversal (postfix representation) abc*t+de*ftg*+ rraversal (prefix representation) Trees ® 6.23 wom ratbort*defg of an expression tree f, rom a Post! suction sonst ¢ fix expression «will 10 discuss the conversion of postfi Wer ady have an algorithm to convert in: a yea sm the two common types of input ees ; waation algorithm. X Expression j nae aaa an expression tree. Since The muthat ne can generate expression Strongly resembles the postfix xpression one We read OUT ; ee hint on at a time. If the symbol is an oietree and p : T to it onto a stack. If the symbol is operand, we cea one wo trees 7, and T, from the stack (7, is popped first) and i eee ane i 3 form i ator and whose left and right children point to 7, and T, repentneh pa is 1 ly. A pointer to he opera tree is then pushed onto the stack. thisne™ truct th i Construct the tree from a given postfix expression a gxample: abtcde+** mbal sy Stack Remark Scanned : - ‘a’is an operand, so we create 3 one node tree and push @) pointer on toa stack. b ‘pb? is an operand, so we create one node tree and push pointer on toa stack. (a) ) + |_| s+? js an operator, so_two pointers to trees are, popped, ‘a new tree is formed, and a pointer to it is pushed on to the stack. a) (by b 6.24 * Data Structures Using C trees are merged. ———$—— *c’ is an operand, Create one node tree and a points to the corresponding tree A pushed on to the stack, . ‘d’ is an operand, create One node tree and a pointer to the tree is pushed on to the stacy, ‘e’ is an operand, create a one node tree and a pointer to the tree is pushed on to the stack. ‘+? is an operator, so two) “# is an operator, SO we pop two tree pointers and form new tree with a <# as 100! node. The last Symbol ‘* is an OPErator, two trees are Merged, and a Pointer to the final tree is left On the stack Figure 6.19 Construction of an Expression tree from a Postfix expression construction of an expression tree from @ prefix expression Inthis we read our expression one symbol at a time? I sone node tree and push a pointer to it onto a Stack. If the symbol is an operator, we pop pointers to two trees T, and T, from the stack (7, is popped first) and form a new tree whose ot is the operator and whose left and tight children point to T, and T, respectively. A pointer to this new tree is then pushed onto the stack. f the symbol is an operand, we create Example: Construct the tree from a given prefix expression ttrabtctde 7 Inthis scan the expression from right to left. Saal | ; Stack Remark Scanned rs Since ‘e’ is an operand so create one node tree and push pointer on to stack. ‘d" is an operand, create one node tree and push pointer on to stack. 6.26 * Data Structures Using C [+ ) Gott oH) @) (¢ “+? is an operator, so we Pop two tree pointers and form new free. The Ist Poped element becomes the left child of the tree and 2nq popped element becomes the right child of the tree. ‘c’ is an operand, create one node tree and push pointer on to stack. “*° is an operator, so we pop two tree pointers and forma new tree. The Ist poped lgment becomes the left child, of the tree and di popped element becomes the | root of the right subtree of the node ‘*” “b’ is an operand, create one node tree and push pointer ou to stack. Trees ® 627 Figure 6.20 Co nstruction of an expres element becomes the root of potas sion tree from a prefix expression ‘a’ is an operand, create one node tree and push pointer on to stack. +’ is an operator, so we pop two tree pointers and form a new tree. The | st_poped the left su left subtree of the tree and 2nd popp popped ele element becomes Serra ee the root of the right subtree of the node ‘+’. The last symbol ‘*” is an operator, two trees are merged and a pointer to the final tree is left on the stack.

You might also like