0% found this document useful (0 votes)
360 views27 pages

Data Structures - Unit-4

Uploaded by

Naresh Babu
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)
360 views27 pages

Data Structures - Unit-4

Uploaded by

Naresh Babu
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/ 27
a : . : ‘TREES uNIT-IV 7 us sis . . ALA! UNIT IV \%8 Trees Introduction Terminology Representation of trees, Binary trees abstract data type Properties of binary trees Binary tree representation Binary tree traversals: In order, preorder, post order Binary search trees Definition Operations:searching BST, insert into BST, delete from a BST, Height of a BST. ‘Trees: Non-Linear data structure A data structure is said to be linear if ts elements form a sequence or a linear list. Previous linear data structures that we have studied like an array, stacks, queues and linked lists organize data in linear order. A data structure is said to be non linear if its elements form a hierarchical classification where, data items appear at various levels. Trees and Graphs are widely used non-linear data structures. Tree and graph structures represent hierarchical relationship between individual data elements. Graphs are nothing but trees with certain restrictions removed. - Trees represent a special case of more general structures known as graphs. In a graph, there is no restrictions on the number of links that can enter or leave a node, and cycles may be present in the graph. The figure 5.1.1 shows a tree and a non-tree. Figure 5.1.1 A Tree and anote bee Tree is a popular data structure used in wi ide range of appli defined as follows ize of applications. A tree data structure can be Tree is a non-linear data structure whic! rarchical stru lich organizes data in hie i eee erarchical structure and this is a A tree data structure can also be defined as follows, A tree is a finite-set of one or more nodes such that: * . 4 ‘Scanned with CamScanner = - : os cs uNiT-1v ; , aT oe he 00 fiodes are partitioned into n>~{ There is a specially designated node called the root. The remaining atree. We call Tl, __, Tn are the subtrees of the disjoint sets TI, .... Tn, where each of these sets is root. “ A tree is hierarchical collection of nodes. One of the nodes, known as the root, is at the top of ‘the . hierarchy, Each node can have at most one link coming into it. The node where the link originates is called the parent node. The root node has no parent. The links leaving a node (any number of links are allowed) point to child nodes. Trees are recursive structures. Each child node is itself the root of _a subtree. At the bottom of the tree are leaf nodes, which have no children. Advantages of trees _ Trees are so useful and frequently used, because they have some very serious advantages: Trees reflect structural relationships in the data Trees are used to represent hierarchies Trees provide an efficient insertion and searching Trees are very flexible data, allowing to move sub trees around with minimum effort Introduction Terminology Ina Tree, Every individual element is called as Node. Node in a tree data structure, stores the actual data of that particular element and link to next element in hierarchical structure, Example _S. TREE with 21 nodes and 10 edges Cay [) > In any tree with “NW” nodes there
    =0. = Abinary tree with n nodes and depth k is complete iff its nodés correspond to the nodes numbered from 1 to n in the full binary tree of depth k. _ Complete binary tree ns 3. Extended Binary Tree A binary tree can be converted into Full Bi i nian te can into ul Binary tee by adding dummy nodes to existing nodes The full binary tree ob tained by addi i me ied by adding dummy nodes to a binary tree is called as Extended Binary Abstract Data Type ‘Scanned with CamScanner * UNIT-IV - S . . TREES Definition: A binary tree is a finite set of nodes that is either empty or consists of a root and two disjoint binary trees called left subtree and right subtree, ADT contains specification for the binary tree ADT Structure Binary_Tree(abbreviated BinTree) is objects: a finite set of nodes either empty or consisting of a root node, left Binary Tree, and right Binary_Tree. Functions: for all bt, b1/, br2 © BinTree, item € element Bintree Create()::= creates an empty binary tree Bootean sEmpty():~ i (bF—emply binary tee) retum TRUE else return FALSE BinTree MakeBT(bi/, item, bt2)::= return a binary tree whose left subtrce is bi/, whose right subtree is 22, and whose root node contains the data item Bintree Lehild(bt)::= if (IsEmpty(bi)) return error ‘else return the left subtree of br element Data(bt):: (IsEmpty(b¢)) return error clse return the data in the root node of br Bintree Rchild(b1)::= if (IsEmpty(b1)) retum error else return the right subtree of br Samples of Trees Complete Binary Tree Differences between A Tree and A Binary Tree + The subtrees of a binary tree are ordered; those of a tree are not ordered. ‘Scanned with CamScanner en viewed as trees. Above two trees are different when viewed as binary (rees. But_ same when view Properties of Binary Trees 1.Maximum Number of Nodes in BT The maximum number of nodes on level i of a binary tree is 2° Vil «The maximum number of nodes in a binary tree of depth k is 2°-1, k>=1 Proof By Induction: Induction Base: The root is the only node on level i=1.Hence ,the maximum number of nodes on evel i=1 is 2"'=2°=1 Induction Hypothesis: Let I be an arbitrary positive integer greater than 1.Assume that maximum number of nodes on level i-I is 2". Induction Step: The maximum number of nodes on level i-l is 2"? by the induction hypothesis. Since cach node in a binary tree has a maximum degree of 2,the maximum number of nodes on level i is ‘two times the maximum number of nodes on level i-1,or 2°. . The maximum number of nodes in a binary tree of depth k is ).2"" a 2.Relation between number of leaf nodes and degree-2 nodes: For any nonempty binary tree, T, if, 1g is the number of leaf nodes and n the number of nodes of degree 2, then n=n2#1 PROOF: Let and B denote the total number of nodes and branches in T. Let mo, m, nz represent the nodes with zero children, single child, and two children respectively. Btl=n > Beny+2m => my+2nztl= n, nyt 2nzt l= ngtny +n => ng=nz+] 3. full binary tree of depth kis a binary tree of depth k having 2 -1 nodes, k>=0. A binary tree with n nodes and d i lepth k i from 1 to n in the full binary tree én Pe ara oa mS Binary Tree Representation A binary tree data structure is repr resented usi mn Representation 2)Linked List ee two methods. Those Methods are 1)Array ‘Scanned with CamScanner “UNT-IV . “ . ‘TREES \)Array Representation: In array representation of binary tree, we use a one dimensional array (1-D Array) to represent a binary tree. To represent a binary tree of depth 'n’ using array representation, we need one dimensional array with a maximum size of ‘A complete binary tree with n nodes (depth = log n + 1) is represented sequentially, then for any node with index i, I<-i<=n, we have: a) parent(i) is at i/2 if i#=1. If i=1, is at the root and has no parent, b\left_child(i) ia at 2i if 2i=n, If 2en, then i has no left child. c) right child(i) is at 2it1 iF 24 +1 n, then has no right child rey Gh tal m ts i te a a1 tat (31 tel tH SS SS tat (1 - © ine) 26s a | We use linked list to represent a binary tree. Ina linked list, every node consists of three fields. First 2. Linked Representation field, for storing left child-address, second for storing actual data and third for storing right child address. In this linked list representation, a node has the following structure... [en cia] aom | vasa | ag right_child typedef struct node *tree_pointer; typedef struct node { int data; tree_pointer left_child, right childs}; : u ‘Scanned with CamScanner root + ve om (emz[e[rwc) Ger Binary Tree Traversals When we wanted to display a binary tree, we need to follow some order in which all the nodes of that binary tree must be displayed. In any binary tree displaying order of nodes depends on the “aversal method. Displaying (or) visiting order of nodes in a binary tree is called as Binary Tree Traversal. - There are three types of binary tree traversals, 1)In - Order Traversal 2)Pre-Order Traversal _3)Post - Order Traversal Binary Tree Traversals 1. In - Order Traversal ( leftChild - root - rightChild ) In In-Order traversal, the root node is visited between left child and right child. In this traversal, the left child node is visited first, then the root node is visited and later we go for visiting right child node. This in-order traversal is applicable for every root node ofall subtrees in the tree. This is performed recursively for all nodes in the tree. In the above example of binary tree, first we try to visit left child of root node ‘A’, but A's left child is 1 rooTnode for left subtree. so we try to visit its (B's left child 'D' and again D is a root for subt with nodes D, Iand J. So we try to visit its let child 'T and itis the let most child. So first we 2 ‘Seanned with CamScanner uNtT-tv a .oe o. TREES visit Then go for is root node" and later we visit D's right child '. With this we have completed the left part of node B. Then visit 'B' and next B's right child 'F’ is visited. With this we have completed left part of node A. Then visit oot node’A: With this we have completed left and root parts of node A. Then we go for ight part ofthe node A. In right of A again there is a subtree with Toot C. So go for left child of C and again it is a subtree with root G. But G does not have left part so we visit Gand then visit G's Tight child K. With this we have completed the left part of node C. Then visit root node'C’ and next Visit C's right child 'H' which is the right most child in the tree so we stop the process, {hat means here we have visited inthe order of 1-D-J-B-F-A-G-K-C-H using In-Order Traversal, {n-Order Traversal for above example of binary tree is 1-D-J-B-F-A-G-kK-c_H - - - Algorithm Until all nodes are traversed — Step I ~ Recursively traverse left subtree. Step 2 ~ Visit root node. Step 3 — Recursively traverse right subtree void inorder(tree_pointer ptr) - /* inorder tree traversal */ Recursive if (ptr) { - inorder(ptr->left_chil prinitf(“%d", ptr->data) indorder(ptr->right_child); ) } - Order Tr I ( root - leftChild - rightChild ) in one traversal, is root node is visited before left child and right child nodes. In this traversal, the root node is visited first, then its left child and later its right child. This pre-order traversal is applicable for every root node of all subtrees in the tree. tree, first we visit root node ‘A’ then vist its left child ‘BY which is a In the above oxen a viet Bis Beh eild'D'endwuin Disa rot fr Land’ Se We Visit D's left root foe the left most child, So next we go for visiting D's right child". With this we have child'l' which is left and right parts of node D and root, left parts of node B. Next visit B's right completed root, lef we have completed root and left parts of node A. So we go for A's right child F. with this root node for G and H. After visiting C, we go for its left child ‘G' which is a toot child ‘C’ whit ° ‘Scanned with CamScanner — — TREES UNIT. Iv - for G's right child » * doe left child so we go TOF 4% NIBNN< . jut it does not ave Next visit C's right child 'H' which is th, root and left pat Se we stop the process, ; Pre-Order Traversal, for node K. So next we visit left of With this we have completed node Cs Feht most child in’ —tht—_—tree 2C-G-K-H usin ‘That means here we have visited in the order of A-B-D-F-F-C-G-K-H using Algorithm Until all nodes are traversed — Step 1 ~ Visit root node Step 2 ~ Recursively traverse left subtree. Step 3 ~ Recursively traverse right subtree. Void preorder(tree_pointer ptr) /* preorder tree traversal */ Recursive af (ptr) Printf(“%d", ptr->data); Preorder(ptr->left_ child); Preorder(ptr->right_child); 1 - } 3. Post - Order Traversal ( leftChild - rightChild - root ) In Post-Order traversal, the root node is visited after left child and right child. In this traversal, left child node is visited first, then its right child and then its root node. This is recursively performed until the right most node is visited. Here we have visited in the order of I-J-D-F -B-K -G-H-C- A using Post-Order Traversal, Algorithm Until all nodes are traversed — Step 1 — Recursively traverse left subtree Step 2 — Recursively traverse right subtree. Step 3 - Visit root node. void postorder(tree_pointer ptr) _/* postorder tree traversal */ Recursive printf(“%d”, ptr->data); . 14 ~ - ‘Scanned with CamScanner UNIT-IV se TREES Ari ithmetic Expression Using BT Iterative Inorder Traversal (using stack) Void iter_inorder(tree_pointer node)~ - { inttop=-1; initialize tack */ - ‘tee_pointer stack{ MAX. STACK. SIZE]; for (3) { for (;node; node-node->left child) add(Etop, node), /* add to stack */ node= deletc(Stop); _/* delete from stack */ if (tnode) break; /* empty stack */ printf(‘%D", node->data), node = node->right_child; } } In iterative ine jorder traversal, we must create our own stack to add and remove nodes as in recursion — is: Letn be numberof nodes inte, evry node of trees placed on and remove fiom the tack exactly once, ae ity is O(n). The space requirement is equal tothe deptrof tree which is O(n. ‘Scanned with CamScanner UNIT-1V. Level Order Traversal (Using Queue) —Teaversa without Sta oid level_order{trce_ pointer par) 7° level order tree traversal */ { int front =rear~0; - {ree pointer queve(MAX_QUEUE_SIZE} if (tpt) retum; /* empty queue */ addq( ont, Srear, ptr); for (;) { Pir= deleteg( efron, rear); — a if(pn) { Printf'%d", ptr>data); . if(prmleA child) — - = = aaddq( front, &rear, ptr>left_child); if(pu>right child) - adda(front, rear, ptr>right_child); } - - else break; } } Level order Traversal is implemented with circular queue. In this onder, we visit the oot firs, then root’s left child followed by root's right child. We continue in this manner, visiting the nodes at each new level from left most to right most nodes. We begin by adding roct tothe queue. The function opcrates by deleting the node a the ffont ofthe queue, printing out the node's data field, and adding the nde's eft and right childkerto the queve: The level onder traversal for above arithmetic expression is+*E *D/CAB. Binary Search Trees Binary Search Tree Representation / Binary Search tree exhibits a special behavior. A node's left child must have value less than its parent's value and node's right child must have value greater than it's parent value. 16 ‘Scanned with CamScanner UNIT:1V TREES ‘We're going to implement tree using node object and connecting them through references. Definition: A binary search tree (BST) is a binary tree, It may be empty. If it is not empty,then all nodes follows the below mentioned properties © Every clement has a unique key. © The keys in a nonempty left subtree (right subtree) are smaller (larger) than the key in the root of subtree. «The keys in a nonempty right subtree larger than the key in the root of subtree © The left and right subtrees are also binary search trees. left sub-tree and right sub-tree and can be defined as ~ left_subtree (keys) < node (key) < right_subtree (keys) é & Fig: Example Binary Scarch Trees ADT for Dictionary: BST Basic Operations The basic operations that can be performed on binary search tree data structure, are following ~ + Search ~ search an element in a binary search tree. + Insert ~ insert an element into a binary search tree / create a tree, + Delete ~ Delete an clement from a binary search tree. + Height Height of a binary search tree. ‘Searching a Binary Search Tree Let an clement k is to search in binary search tree. Start search from root node of the search tree. If | root is NULL, search tree contains no nodes and search unsuccessful. Otherwise, compare k with the key in the root. If k equals the root's key, terminate search, if kis less than key value, search 7 ‘Scanned with CamScanner a . TREES unir-w «The function search recursive, ‘ ree. 7 subir . element k in right su clement k in left subtree otherwise search element searches the subtrees. . any Search Tree Algorithm:Recursive search of a Binary Search Tt tree_pointer search(tree_pointer wot, int key) hs te that contains key. If there is m0. such Fetum a pointer tthe nod node, retum NULL */ if (!root) retum NULL; if (Key = root-data) return root; ~ if (key < root-data) retum search(root-left child, key); Tetum search(root->right_child,key); } Algorithm: Iteraive search of a Binary Search Tree - ‘Wee_pointer search2(tree_pointer tre, int key) - t while (tree) { ‘if (key = tree data) retum tree; if (key < wee->data) _ ‘wee = teeleft- child; else tee = tree->right:-child; _ ; = reumNULL; ” ) Analysis of Recursive search and Iterative Search Algorithms: . ; [his the height ofthe binary search tree, both algorithms perform seach in Ofh) time. Recursive search requires ackitonal tack space which is O(h). Inserting into a Binary Search Tree , The very first insertion creates the tree. Afterwards, whenever an element is to be inserted. First locate its proper locaton, Start search from root node then if data isles than key value, search empty location in left sub tree and insert the data. Otherwise search empty location in right sub tree and insert the data. 18 ‘Scanned with CamScanner tree TREES” > the insertion i Search tree, new node ig always in day 'S Performed with O(log n) time complexity. In binary follows... serted asa leaf node. The 'nsertion operation is performed as Step 1: Create ith . ep 1: Created newNode with Biven value and set itslef and right to NULL. Step 2: Check whether tree ig Empty. ~ - Step 3: If the tree is Empty, then set set root to newNode, i Step 4: If the tree is Not Empty, then check whether Value of newNode is smaller or larger than the ng node (here it is root node), — — Step 5: IfnewNode is smaller than or equal to the node, then move to its left child. If newNode is larger than the node, then move to its right child Step 6: Repeat the above step until we reach a node (ei, reach to NULL) where search terminates Step 7: After reaching a last node, then insert the newNode as let child if newNode is smaller or qual to that node else insert it as right child. : 50 ~ Insert 80 Insert 35 Algorithm ° Create newnode If root is NULL. then create root node retum If root exists then compare the data with node.data «accion $e Incated while until insertion position is locate If data is greater than node.data er ‘Scanned with CamScanner UNIT- IV. 6 right subtree else goto left subtree endwhile insert newnode end If Implementation The implementation of insert function should look like this Void insert(int data) { struct node *tempNode = (struct node*) malloc(sizeof(struct node)); struct node *current; struct node *parent; tempNode->data = data; — tempNode->leftChild = NULL; tempNode->rightChild = NULL; Jf tree is empty, create root node if(root = NULL) { root = tempNode; jelse { : ~ current = root; parent = NULL; while(1) { parent = current; /Igo to left of the tree if(data < parent->data) { current = current->leftChild; . Hfinsert to the left if(current = NULL) { = parent->leftChild = tempNode: ‘Scanned with CamScanner 20 Deleting a node Remove oper: “TREES "90 to right of the tree else { Surrent = curreni->rightChild; Hinsert to the right if{current == NULL) { Parent->rightChild = tempNode; 7 return; on on binary search tree is more complicated, than insert and search Basically, in can be divided into two stages: * search for a node to remove * ifthe node is found, run remove algorithm, > Remove algorithm in detail Now, let's see more detailed descri for are three cases, which are described below. I.Node to be removed has no children, ~This case is link of the parent to NULL and disposes the node. ption of a remove algorithm. First stage is identical to algorithm + lookup, except we should track the parent of the current node. Second partis more tricky. There quite simple. Algorithm sets corresponding Example. Remove -4 from a BST. ‘Scanned with CamScanner n ‘UNIT-IV ) w® AHA ® ( ree and algaritl 2.Node to be removed has one child. In this case, node is cut from we 4 single child (with it’s subtree) directly to the parent of the removed no thm links | 3.Node to be removed has two children. --This is the most complex case. The deleted node can be replaced by cither largest key in its left subtree or the smallest in its right subtree. Preferably which node has one child, Deletion Operation in BST Ina binary search tee, the deletion operation is performed with O(log n) time complexity. Deleting anode from Binary search tree has following three cases. Case 1: Deleting a Leaf node (A node with no children) Case 2: Deleting a node with one child 22 ‘Scanned with CamScanner } yNIT-1V . REES + Case 3: Deleting a node with two children " Case 1: Deleting a leaf node ‘Weruse the following steps to delete a leat node fom BST. Step 1: Find the node to be deleted using search operation Step 2: Delete the node using free function (Ifit isa leaf) and terminate the funetion, Case 2: Deleting a node with one child ‘We use the following steps to delete a node with ‘one child from BST. Step 1: Find the node to be deleted using search operation Step 2: If it has only one child, then create a link between its parent and child nodes. Step 3: Delete the node using free function and terminate the function. Case 3: Deleting a node with two children We use the following steps to delete a node with two children from BST... Step 1: Find the node to be deleted using search operation Step 2: If it has two children, then find the largest node in its left subtree (OR) the smallest node in its right subtree. Step 3: Swap both deleting node and node which found in above step. Step 4: Then, check whether deleting node came to case 1 or case 2 else goto steps 2 Step 5: If it comes to case 1, then delete using case 1 logic. Step 6: If it comes to case 2, then delete using case 2 logic. Step 7: Repeat the same process until node is deleted from the tree. /* deletion in binary search tree */ void deletion(struct treeNode **node, struct treeNode **parent, int data) { struct treeNode *tmpNode, *tmpParent; if (*node == NULL) return; data) ( f ((*node)->data = data) { me /* deleting theleafnode */ _ if ((¢mode)->left && !(*node) right) { ent) { (Per elec leat node */ 2B ‘Scanned with CamScanner UNITHIVS Lt : if ((*parent)->lef — *node) (*parent)->left = NULL; else (¢parent)->right = NULL; firee(*node); } else { /* delete root node with no children */ free(*node); } /* deleting node with one child */ } else if (!(*node)->right && (*node)->left) { /* deleting node with left child alone */ tmpNode = *node; (*parent)->right = free(tmpNode); *node = (*parent)->right; } else if ((*node)->right && \(*node)->left) { /* deleting node with right child alone */ tmpNode = *node; (*parent)->left = (*node)->right; free(tmpNode); (*node) = (*parent)->left; } else if (1(*node)->right->left) { * deleting a node whose right child * is the smallest node in the right * subtree for the node to be deleted ” 7 *node)->left; tmpNode = *node; (*node)->right->left = (*node)->teft, (*parent)->left = (*node)->right; free(tmpNode); *node = (*parent)->left; J else { * * Deleting a node with two children. * First, find the smallest node in * the right subtree. Replace the - * smallest node with the node to be + deleted. Then, do proper connections * for the children of replaced node. “7 tmpNode = (*node)->right; 7 while (tmpNode->lef) { 24 eee ‘Scanned with CamScanner TR tmpParent = tmpNode; nes 7 oy tmpNode = tmpNode->left; tmpParent->left = tmpNode->right; impNode- teh = (*node)sien _tmpNode->right =(*node)->right, free(*node); “node = tmpNode; } } else if (data < (*node)->data) { /* traverse towards left subtree */ ae deletion(&(*node)-left, node, data); } else if (data > (*node)->data) { /* traversing towards right subtree */ ) deletion(&(*node)->right, node, data), } Height of a Binary Search Tree: Height of a Binary Tree For a tree with just one node, the root node, the height is defined to be 0, if there are 2 levels of nodes the height is | and so on. A null tree (no nodes except the null node) is defined to have a height of 1 “The following height function in pseudocode is defined recursively int height( BinaryTree Node t) ¢ if tis a null tree return -1; reight( left subtree of ty, - hr = height( right subtree of t) h= 1+ maximum of hl and hr: return h: ‘Scanned with CamScanner_ | UNIT-IV 7 ts left subtree has height 2 and its For example, the following tree has a height of 4.1 right subtice 3 21 Example — Construct a Binary Search Tree by inserting the following sequence of numbers... 10,12, 1.20,8,7,15 and 13, Above elements are inserted into a Binary Search Tree as follows... $$ ‘Scanned with CamScanner insert (10) insert (4) (20) insert (7) insert (12) Q2) insert (20) insert (15) TREES insert (5) 6G) @ insert (8) (20) — fk @& o@®™ © @ insert (13) ‘Scanned with CamScanner

You might also like