Module 04 Trees Contents

Size: px
Start display at page:

Download "Module 04 Trees Contents"

Transcription

1 Module 04 Trees Contents Chethan Raj C Assistant Professor Dept. of CSE 1. Trees Terminology 2. Binary Trees, Properties of Binary trees 3. Array and linked Representation of Binary Trees 4. Binary Tree Traversals -Inorder, postorder, preorder 5. Additional Binary tree operations. 6. Threaded binary trees, 7. Binary Search Trees Definition, Insertion, Deletion, Traversal, Searching, Application of Trees-Evaluation of Expression 8. Programming Examples. Chethan Raj C, Assistant Professor, Dept. of CSE Page 1

2 Trees In linear data structure, data is organized in sequential order and in non-linear data structure, data is organized in random order. Unlike Arrays, Linked Lists, Stack and queues, which are linear data structures, trees are hierarchical data structures. Tree is a very popular data structure used in wide range of applications. A tree data structure can be defined as follows. Tree is a non-linear data structure which organizes data in hierarchical fashion and the tree structure follows a recursive pattern of organizing and storing data. The use of trees stores the information by forming in an hierarchy manner. For example, the file system on a computer: 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. if there are N number of nodes in a tree structure, then there can be a maximum of N-1 number of links. Example A tree is a collection of elements called nodes. Each node contains some value or element. The term called node is used rather than vertex with binary tree. Node is the main component of any tree structure. It stores the actual data along with links to other nodes. Key properties of Tree A tree T is represented by nodes and edges, which includes: 1.T is empty (called null or empty tree). 2.T has a left subtree and right subtree. Tree features/characteristics 1. Trees (with some ordering e.g., BST) provide moderate access/search (quicker than Linked List and slower than arrays). 2. Trees provide moderate insertion/deletion (quicker than Arrays and slower than Unordered Linked Lists). 3. Like Linked Lists and unlike Arrays, Trees don t have an upper limit on number of nodes as nodes are linked using pointers. Chethan Raj C, Assistant Professor, Dept. of CSE Page 2

3 The applications of trees include: 1. Manipulate the hierarchical data. 2. Make information easy to search (see tree traversal). 3. Manipulate sorted lists of data. 4. As a workflow for compositing digital images for visual effects. 5. Router/Routing algorithms in computer networks. 6. Form of a multi-stage decision-making (business chess). Consider the following Tree: Fig 1 Fig 2 Trees Terminologies: Node: A tree is a collection of entities called nodes. Nodes are connected by edges. Each node contains a value or data, and node may or may not have a child node. 1. Root Node This is the unique node in the tree in which further subtrees were attached. A root node of a tree has its child i.e left child and right child are the two children of a root node in a tree. In the given figure 2 A is the root node.( The first node of the tree is called the root node). 2. Degree of Node The total number of subtree attached to that node is called the degree of the node. For node A the degree is 3, for node E the degree is 0. ( figure 2) 3. Leaf Nodes These are the terminals nodes of the tree. The nodes which have degree 0 are called as leaf nodes of the tree. These nodes are always present at the end of the tree. Here in our example E, F, C, G, H are the leaf nodes of the tree. ( figure 2) 4. Internal Nodes The nodes in the tree which are other than leaf nodes and the root node are called as internal nodes. These nodes are present in between root node and leaf nodes in the tree that s why these nodes are called as internal node. Here, B and D are internal nodes.( figure 2) 5. Siblings Chethan Raj C, Assistant Professor, Dept. of CSE Page 3

4 In a tree data structure, nodes which belong to same Parent are called as SIBLINGS. In simple words, the nodes with same parent are called as Sibling nodes.ex: B & C are siblings, D, E and F are siblings, G & H are siblings, I & J are siblings.( figure 1) 5. Parent Node The node which is having further sub branches is called the parent node of those sub branches. In the above figure node B is the parent node of E, F, and G node and E, F, and G are called children of B.( figure 2) 6. Predecessor While displaying the tree, if some particular nodes previous to some other nodes than that node is called the predecessor of the other node. In our example, the node E is predecessor of node B.( figure 2) 7. Successor The node which occurs next to some other node is called successor of that node. In our example, B is successor of F and G.( figure 2) 8. Level of tree The root node is always considering at level zero, and then its adjacent children are supposed to be at level 1 and so on. To understand the concept of level, see the above figure, the node A is at level 0, the node B, C, Dare at level 1, the nodes E, F, G, H are at level 2.( figure 2) 9. Height of the tree In a tree data structure, the total number of egdes from leaf node to a particular node in the longest path is called as HEIGHT of that Node. In a tree, height of the root node is said to be height of the tree. In a tree, height of all leaf nodes is '0'. The maximum level is the height of the tree. Here the height of the tree is 3. The other terminology used for the height of the tree is depth of the tree.( figure 2) Depth Chethan Raj C, Assistant Professor, Dept. of CSE Page 4

5 In a tree data structure, the total number of egdes from root node to a particular node is called as DEPTH of that Node. In a tree, the total number of edges from root node to a leaf node in the longest path is said to be Depth of the tree. In simple words, the highest depth of any leaf node in a tree is said to be depth of that tree. In a tree, depth of the root node is '0'. Path In a tree data structure, the sequence of Nodes and Edges from one node to another node is called as PATH between the two Nodes. Length of a Path is total number of nodes in that path. In below example the path A - B - E - J has length 4. Uses of tree 1. Used for storing and retrieving information 2. Used for Insert, delete, and search faster than with a linked list 3. Binary trees are a good way to express arithmetic expressions. 10. Forest A tree may be defined as a forest in which only a single node (root) has no predecessor Any forest is consist of collection of trees. 11. Degree of tree The maximum degree of the node in the tree is called the degree of the tree. Here, the degree of tree is 3. Sub Tree Chethan Raj C, Assistant Professor, Dept. of CSE Page 5

6 In a tree data structure, each child from a node forms a subtree recursively. Every child node will form a subtree on its parent node. The ancestors of a node are all the nodes along the path from the root to that node. Ex: ancestor of j is B & A A forest is a set of n 0 disjoint trees. The notion of a forest is very close to that of a tree because if we remove the root of a tree we get a forest. For example, in figure 1 if we remove A we get a forest with three trees. An ancestor is any element which is connected further up in the hierarchy tree no matter how many levels higher. Ex: node 1 is ancestor of node 6, node 1 is not an ancestor of node 7. A descendant refers to any element that is connected lower down the hierarchy tree no matter how many levels lower. Ex: node 4 has one descendent 6, node 1 has two descendent 3 & 4. All node in the tree under 0 are descendants. Binary Tree. A tree is said to be binary tree when, Chethan Raj C, Assistant Professor, Dept. of CSE Page 6

7 1. A binary tree has a root node. It may not have any child nodes(0 child nodes, NULL tree). 2. A root node may have one or two child nodes. Each node forms a binary tree itself. 3. The number of child nodes cannot be more than two. 4. It has a unique path from the root to every other node. Binary Tree A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right child. Fig: Binary Tree Binary Tree Representation in C A tree is represented by a pointer to the topmost node in tree. If the tree is empty, then value of root is NULL. A node in a tree contains following parts. 1. Data. 2. Pointer to left child.(left link) 3. Pointer to right child. (Right link) A node of a binary tree is represented by a structure containing a data part and two pointers to other structures of the same type. struct node int data; struct node *left; struct node *right; ; A special pointer called ROOT points to the node that is the parent of all the other nodes. Also, the nodes that don't have any children have their left and right pointers point to NULL. Ex: struct node int data; struct node *left; struct node *right; ; Chethan Raj C, Assistant Professor, Dept. of CSE Page 7

8 /* newnode() allocates a new node with the given data and NULL left and right pointers. */ struct node* newnode(int data) // Allocate memory for new node struct node* node = (struct node*)malloc(sizeof(struct node)); // Assign data to this node node->data = data; // Initialize left and right children as NULL node->left = NULL; node->right = NULL; return(node); int main() /*create root*/ struct node *root = newnode(1); /* following is the tree after above statement */ 1 / \ NULL NULL root->left root->right = newnode(2); = newnode(3); /* 2 and 3 become left and right children of 1 1 / \ 2 3 / \ / \ NULL NULL NULL NULL */ root->left->left = newnode(4); /* 4 becomes left child of 2 1 / \ 2 3 / \ / \ 4 NULL NULL NULL / \ NULL NULL */ getchar(); return 0; Chethan Raj C, Assistant Professor, Dept. of CSE Page 8

9 In a general tree, every node can have arbitrary number of children but binary tree is a special type of tree data structure in which every node can have a maximum of 2 children. One is known as left child and the other is known as right child. A tree in which every node can have a maximum of two children is called as Binary Tree. In a binary tree, every node can have either 0 children or 1 child or 2 children but not more than 2 children. Binary Tree is the most basic form of tree structure. Where each node can have utmost two children. A binary tree is a finite set of nodes that is either empty or consist a root node and two disjoint binary trees called the left subtree and the right subtree. In other words, a binary tree is a non-linear data structure in which each node has maximum of two child nodes. The tree connections can be called as branches. A perfect binary tree is a binary tree in which all interior nodes have two children and all leaves have the same depth or same level. A full binary tree (sometimes referred to as a proper[15] or plane binary tree) is a tree in which every node in the tree has either 0 or 2 children. In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. In the infinite complete binary tree, every node has two children. A linked list is a chain of nodes connect through "next" pointers. A tree is similar, but each node can be connected to multiple nodes.tree is a structure that has two children, left and right. NOTE: 1. The number of edges from the root to the node is called Depth of the tree. 2. The number of edges from the node to the deepest leaf is called Height of the tree 3. In a full binary tree if number of internal nodes is I, then number of leaves L are L=i In a full binary tree if number of internal nodes is I, then number of nodes N are N= 2I+1 5. In a full binary tree if there are L leaves, then total number of nodes N are N=2L-1 Binary search tree(bst): BST is a binary tree with certain properties such as, and left child of the given node contains value less than equal to the given node and right hand child contain node greater than the given node. A binary tree is a tree data structure in which each node has at most two children, which are referred to as the left child and the right child. Chethan Raj C, Assistant Professor, Dept. of CSE Page 9

10 2. Binary Search Tree: Binary Search Tree follow (Left.Value<Root<Rightchild.value) Rule *The major advantage of binary search trees over other data structures is that the related sorting algorithms and search algorithms such as in-order traversal can be very efficient; they are also easy to code. *Binary search trees are a fundamental data structure used to construct more abstract data structures such as sets, multisets, and associative arrays. Types of Trees: 1. Full /strictly Binary Tree 2. Complete Binary Tree 3. Almost complete binary tree 4. Skewed Binary Tree 5. Extended Binary Tree 6. Rooted Binary tree Chethan Raj C, Assistant Professor, Dept. of CSE Page 10

11 1. Rooted Binary Tree- Rooted binary tree is a binary tree that has a root node and every node has at most 2 children. Full Binary Tree If each node of binary tree has either two children or no child at all, is said to be a Full Binary Tree. Full binary tree is also called as Strictly Binary Tree. Every node in the tree has either 0 or 2 children. Full binary tree is used to represent mathematical expressions. A full / strictly binary tree is a binary tree in which every node has either 0 or 2 children. Complete/perfect Binary Tree If all levels of tree are completely filled except the last level and the last level has all keys as left as possible, is said to be a Complete Binary Tree. Complete binary tree is also called as Perfect Binary Tree. Chethan Raj C, Assistant Professor, Dept. of CSE Page 11

12 In a complete binary tree, every internal node has exactly two children and all leaf nodes are at same level. For example, at Level 2, there must be 22 = 4 nodes and at Level 3 there must be 23 = 8 nodes. Perfect binary tree: A complete / perfect binary tree is a binary tree in which every internal node has exactly 2 children and all the leaf nodes are at the same level. Skewed Binary Tree If a tree which is dominated by left child node or right child node, is said to be a Skewed Binary Tree. In a skewed binary tree, all nodes except one have only one child node. The remaining node has no child. Chethan Raj C, Assistant Professor, Dept. of CSE Page 12

13 In a left skewed tree, most of the nodes have the left child without corresponding right child. In a right skewed tree, most of the nodes have the right child without corresponding left child. Extended Binary Tree Extended binary tree consists of replacing every null subtree of the original tree with special nodes. Empty circle represents internal node and filled circle represents external node. The nodes from the original tree are internal nodes and the special nodes are external nodes. Every internal node in the extended binary tree has exactly two children and every external node is a leaf. It displays the result which is a complete binary tree. Almost Complete Binary Tree An almost complete binary tree is a binary tree in which all the levels are completely filled except possibly the last level and the last level must be strictly filled from left to right. Balanced binary tree: It is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Return 0 / 1 ( 0 for false, 1 for true ) for this problem Chethan Raj C, Assistant Professor, Dept. of CSE Page 13

14 Input : 1 / \ 2 3 Return : True or 1 Input 2 : 3 / 2 / 1 Return : False or 0 Because for the root node, left subtree has depth 2 and right subtree has depth 0. Difference = 2 > 1. Example 1: Given the following tree [3,9,20,null,null,15,7] 3 / \ 9 20 / \ 15 7 Return true. Example 2: Given the following tree [1,2,2,3,3,null,null,4,4] 1 / \ 2 2 / \ Chethan Raj C, Assistant Professor, Dept. of CSE Page 14

15 3 3 / \ 4 4 Return false. Properties of Binary trees A binary tree is a special case of an ordered binary tree, where k is 2. Trees are used to represent data in hierarchical form. Binary tree is the one in which each node has maximum of two child- node. The order of binary tree is 2. Binary tree does not allow duplicate node values(data). While constructing a binary, if an element is less than the value of its parent node, it is placed on the left side of it otherwise right side. A binary tree is shown for the element 40, 56, 35, 48, 22, 65, 28. The several properties of Binary Tree are 1) Minimum number of nodes in a binary tree of height H = H + 1 Example- To construct a binary tree of height = 4, we need at least = 5 nodes 2) Maximum number of nodes in a binary tree of height H = 2 ^ H+1 1 Chethan Raj C, Assistant Professor, Dept. of CSE Page 15

16 Example- Maximum number of nodes in a binary tree of height = 3 = = 16 1 = 15 User can not insert more number of nodes in this binary tree. Thus, in a binary tree of height =3, maximum number of nodes that can be inserted = 15. Note: Maximum number of nodes in a binary tree of height h is 2 h 1 3) Total Number of leaf nodes in a Binary Tree = Total Number of Degree-2 nodes + 1 It is very important to note from here that the number of leaf nodes in any binary tree depends only on the number of degree-2 nodes. Example- Consider the following binary tree- Here, Number of leaf nodes = 3 Number of degree-2 nodes = 2 Chethan Raj C, Assistant Professor, Dept. of CSE Page 16

17 This verifies the above relation. 4) Maximum number of nodes at any level L in a binary tree = 2L Maximum number of nodes at level = 2 in a binary tree(2^l) = 2 2 = 4 Thus, in a binary tree, maximum number of nodes that we can have at level-2 = 4. Note: The maximum number of nodes at level l of a binary tree is 2l-1. A binary tree of height h has at least h and at most 2h - 1 elements/nodes/data. 5) A binary tree of n elements(nodes) has n-1 edges (This is true for any kind of tree.) Handshaking lemma Tree Properties. 1) In a k-ary tree where every node has either 0 or k children, following property is always true. L = (k - 1)*I + 1 Where L = Number of leaf nodes I = Number of internal nodes Proof: Proof can be divided in two cases. Case 1 (Root is Leaf):There is only one node in tree. The above formula is true for single node as L = 1, I = 0. Case 2 (Root is Internal Node): For trees with more than 1 nodes, root is always internal node. The above formula can be proved using Handshaking Lemma for this case. A tree is an undirected acyclic graph. Total number of edges in Tree is number of nodes minus 1, i.e., E = L + I 1. All internal nodes except root in the given type of tree have degree k + 1. Root has degree k. All leaves have degree 1. Applying the Handshaking lemma to such trees, we get following relation. Sum of all degrees = 2 * (Sum of Edges) Chethan Raj C, Assistant Professor, Dept. of CSE Page 17

18 Sum of degrees of leaves + Sum of degrees for Internal Node except root + Root's degree = 2 * (No. of nodes - 1) Putting values of above terms, L + (I-1)*(k+1) + k = 2 * (L + I - 1) L + k*i - k + I -1 + k = 2*L + 2I - 2 L + K*I + I - 1 = 2*L + 2*I - 2 K*I I = L (K-1)*I + 1 = L So the above property is proved using Handshaking Lemma, let us discuss one more interesting property. 2) In Binary tree, number of leaf nodes is always one more than nodes with two children. L = T + 1 Where L = Number of leaf nodes T = Number of internal nodes with two children Proof: Let number of nodes with 2 children be T. Proof can be divided in three cases. Case 1: There is only one node, the relationship holds as T = 0, L = 1. Case 2: Root has two children, i.e., degree of root is 2. Sum of degrees of nodes with two children except root + Sum of degrees of nodes with one child + Sum of degrees of leaves + Root's degree = 2 * (No. of Nodes - 1) Putting values of above terms, (T-1)*3 + S*2 + L + 2 = (S + T + L - 1)*2 Cancelling 2S from both sides. (T-1)*3 + L + 2 = (S + L - 1)*2 T - 1 = L - 2 T = L - 1 Case 3: Root has one child, i.e., degree of root is 1. Chethan Raj C, Assistant Professor, Dept. of CSE Page 18

19 Sum of degrees of nodes with two children + Sum of degrees of nodes with one child except root + Sum of degrees of leaves + Root's degree = 2 * (No. of Nodes - 1) Putting values of above terms, T*3 + (S-1)*2 + L + 1 = (S + T + L - 1)*2 Cancelling 2S from both sides. 3*T + L -1 = 2*T + 2*L - 2 T - 1 = L - 2 T = L - 1 Therefore, in all three cases, we get T = L-1. Advantages of Binary Tree: 1. Searching in Binary tree become faster. 2. Binary tree provides six traversals. 3. Two of six traversals give sorted order of elements. 4. Maximum and minimum elements can be directly picked up. 5. It is used for graph traversal and to convert an expression to postfix and prefix forms. Array and linked Representation of Binary Trees, A binary tree data structure is represented using different methods. Those methods are as follows Array Representation 2. Linked List Representation 3. Left Child - Right Sibling Representation 4. Degree two Representation (Binary Tree Representation) 1. Array Representation In array representation of binary tree, we use a one dimensional array (1-D Array) to represent a binary tree. A single array can be used to represent a binary tree. For these nodes are numbered / indexed according to a scheme giving 0 to root. Then all the nodes are numbered from left to right level by level from top to bottom. Empty nodes are also numbered. Then each node having an index i is put into the array as its ith element. In the figure shown below the nodes of binary tree are numbered according to the given scheme. Chethan Raj C, Assistant Professor, Dept. of CSE Page 19

20 Consider the above example of binary tree and it is represented as follows... To represent a binary tree of depth 'n' using array representation, we need one dimensional array with a maximum size of 2^(n+1) Linked List Representation I n this representation, we use two types of nodes one for representing the node with data and another for representing only references. We start with a node with data from root node in the tree. Then it is linked to an internal node through a reference node and is linked to any other node directly. This process repeats for all the nodes in the tree. The above tree example can be represented using List representation as follows. Binary trees can be represented by links where each node contains the address of the left child and the right child. If any node has its left or right child empty then it will have in its respective link field, a null value. A leaf node has null value in both of its links. Chethan Raj C, Assistant Professor, Dept. of CSE Page 20

21 The structure defining a node of binary tree in C is as follows. Struct node struct node *lc ; /* points to the left child */ int data; /* data field */ struct node *rc; /* points to the right child */ Left Child - Right Sibling Representation In this representation, we use list with one type of node which consists of three fields namely Data field, Left child reference field and Right sibling reference field. Data field stores the actual value of a node, left reference field stores the address of the left child and right reference field stores the address of the right sibling node. Graphical representation of that node is as follows. User can use the double linked list to represent a binary tree. In a double linked list, every node consists of three fields. First 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. (or) In this representation, every node's data field stores the actual value of that node. If that node has left child, then left reference field stores the address of that left child node otherwise that field stores NULL. If that node has right sibling then right reference field stores the address of right sibling node otherwise that field stores NULL. The above tree example can be represented using Left Child - Right Sibling representation as follows. Chethan Raj C, Assistant Professor, Dept. of CSE Page 21

22 Binary Tree Traversals Tree traversal is a method of visiting the nodes of a tree in a particular order. The tree nodes are visited exactly once and displayed as they are visited. 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 1. In - Order Traversal ( leftchild - root - rightchild ) 1 First, visit all the nodes in the left subtree 2 Then the root node 3 Visit all the nodes in the right subtree Chethan Raj C, Assistant Professor, Dept. of CSE Page 22

23 void inorder(struct node*root) if(root) inorder(root->left); //Go to left subtree printf("%d ",root->data); //Printf root->data inorder(root->right); //Go to right subtree 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 of all subtrees in the tree. This is performed recursively for all nodes in the tree. Consider the following binary 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 a root node for left subtree. so we try to visit its (B's) left child 'D' and again D is a root for subtree with nodes D, I and J. So we try to visit its left child 'I' and it is the left most child. So first we visit 'I' then go for its root node 'D' and later we visit D's right child 'J'. 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 root node 'A'. With this we have completed left and root parts of node A. Then we go for right part of the node A. In right of A again there is a subtree with root 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 'G' and then visit G's right 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. That means here we have visited in the order of I - D - J - B - F - A - G - K - C - H using In-Order Traversal. In-Order Traversal for above example of binary tree is: I - D - J - B - F - A - G - K - C H Pre - Order Traversal ( root - leftchild - rightchild ). 1 Visit root node 2 Visit all the nodes in the left subtree 3 Visit all the nodes in the right subtree Chethan Raj C, Assistant Professor, Dept. of CSE Page 23

24 void perorder(struct node*root) if(root) printf("%d ",root->data); //Printf root->data preorder(root->left); //Go to left subtree preorder(root->right); //Go to right subtree In Pre-Order traversal, the 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. In the above example of binary tree, first we visit root node 'A' then visit its left child 'B' which is a root for D and F. So we visit B's left child 'D' and again D is a root for I and J. So we visit D's left child 'I' which is the left most child. So next we go for visiting D's right child 'J'. With this we have completed root, left and right parts of node D and root, left parts of node B. Next visit B's right child 'F'. With this we have completed root and left parts of node A. So we go for A's right child 'C' which is a root node for G and H. After visiting C, we go for its left child 'G' which is a root for node K. So next we visit left of G, but it does not have left child so we go for G's right child 'K'. With this we have completed node C's root and left parts. Next visit C's right child 'H' which is the right most child in the tree. So we stop the process. That means here we have visited in the order of A-B-D-I-J-F-C-G-K-H using Pre-Order Traversal. Pre-Order Traversal for above example binary tree is A - B - D - I - J - F - C - G - K - H 3. Post - Order Traversal ( leftchild - rightchild - root ) 1 visit all the nodes in the left subtree 2 visit the root node 3 visit all the nodes in the right subtree void postorder(struct node*root) if(root) postorder(root->left); //Go to left sub tree postorder(root->right); //Go to right sub tree printf("%d ",root->data); //Printf root->data 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. Chethan Raj C, Assistant Professor, Dept. of CSE Page 24

25 Post-Order Traversal for above example binary tree is : I - J - D - F - B - K - G - H - C - A Note : Refer class notes for Examples Applications of tree traversals The algorithms above have several use cases in software and development. Below is a list of some of these common cases: 1) To construct any binary tree, you need the in-order traversal array of nodes and either a pre-order or post-order array. 2) A binary search tree can be constructed using only its pre-order traversal array. 3) The in-order traversal of a binary search tree produces the elements in sorted order. 4) User can perform a breadth-first search on a tree using a level-order traversal. Level Order Traversal Level order traversal is a method of traversing the nodes of a tree level by level as in breadth first traversal. Level order traversal uses queue thus avoiding stack space usage. Here the nodes are numbered starting with the root on level zero continuing with nodes on level 1,2,3.. The nodes at any level is numbered from left to right Visiting the nodes using the ordering of levels is called level order traversal Queue uses FIFO principle The level order traversal of the above tree is F B G A D I C E H Implementation of level order traversal void Level_Order(node *root) Chethan Raj C, Assistant Professor, Dept. of CSE Page 25

26 int f = 0, r = -1; //global declaration node *q[size], *cur; q[++r] = root; while( r >= f) cur = q[f++]; printf( %d, cur->data); if(cur->lptr!= NULL) q[++r] = cur->lptr; if(cur->rptr!= NULL) q[++r] = cur->lptr; C Implementation for tree traversal: #include <stdio.h> #include <stdlib.h> struct node int value; node* left; node* right; ; struct node* root; struct node* insert(struct node* r, int data); void inorder(struct node* r); void preorder(struct node* r); void postorder(struct node* r); int main() root = NULL; int n, v; printf("how many data's do you want to insert?\n"); scanf("%d", &n); for(int i=0; i<n; i++) printf("data %d: ", i+1); scanf("%d", &v); root = insert(root, v); printf("inorder Traversal: "); inorder(root); printf("\n"); printf("preorder Traversal: "); preorder(root); printf("\n"); printf("postorder Traversal: "); postorder(root); printf("\n"); return 0; struct node* insert(struct node* r, int data) Chethan Raj C, Assistant Professor, Dept. of CSE Page 26

27 if(r==null) r = (struct node*) malloc(sizeof(struct node)); r->value = data; r->left = NULL; r->right = NULL; else if(data < r->value) r->left = insert(r->left, data); else r->right = insert(r->right, data); return r; void inorder(struct node* r) if(r!=null) inorder(r->left); printf("%d ", r->value); inorder(r->right); void preorder(struct node* r) if(r!=null) printf("%d ", r->value); preorder(r->left); preorder(r->right); void postorder(struct node* r) if(r!=null) postorder(r->left); postorder(r->right); printf("%d ", r->value); Additional Binary tree operations. Copying Binary Trees : User can modify the postorder traversal algorithm only slightly to copy the binary tree Testing Equality : Binary trees are equivalent if they have the same topology and the information in corresponding nodes is identical the same topology and data as Program Creation of Binary Tree Using Recursion Chethan Raj C, Assistant Professor, Dept. of CSE Page 27

28 Binary tree creation Algorithm A binary tree can be created recursively. The program will work as follow: 1. Read a data in x. 2. Allocate memory for a new node and store the address in pointer p. 3. Store the data x in the node p. 4. Recursively create the left subtree of p and make it the left child of p. 5. Recursively create the right subtree of p and make it the right child of p. The program is written in C language which allows linked representation of binary tree. Program to Create Binary Tree in C Using Recursion #include<stdio.h> typedef struct node int data; struct node *left; struct node *right; node; node *create() node *p; int x; printf("enter data(-1 for no data):"); scanf("%d",&x); if(x==-1) return NULL; p=(node*)malloc(sizeof(node)); p->data=x; printf("enter left child of %d:\n",x); p->left=create(); printf("enter right child of %d:\n",x); p->right=create(); return p; void preorder(node *t) //address of root node is passed in t if(t!=null) printf("\n%d",t->data); preorder(t->left); preorder(t->right); int main() node *root; root=create(); printf("\nthe preorder traversal of tree is:\n"); //visit the root //preorder traversal on left subtree //preorder traversal om right subtree Chethan Raj C, Assistant Professor, Dept. of CSE Page 28

29 preorder(root); return 0; Ex: #include<stdio.h> typedef struct node int data; struct node *left; struct node *right; node; node *create() node *p; int x; printf("enter data(-1 for no data):"); scanf("%d",&x); if(x==-1) return NULL; p=(node*)malloc(sizeof(node)); p->data=x; printf("enter left child of %d:\n",x); p->left=create(); printf("enter right child of %d:\n",x); p->right=create(); return p; void preorder(node *t) //address of root node is passed in t if(t!=null) printf("\n%d",t->data); //visit the root preorder(t->left); //preorder traversal on left subtree preorder(t->right); //preorder traversal om right subtree int main() node *root; root=create(); printf("\nthe preorder traversal of tree is:\n"); preorder(root); return 0; Output Enter data(-1 for no data):5 Enter left child of 5: Enter data(-1 for no data):7 Enter left child of 7: Enter data(-1 for no data):8 Enter left child of 8: Chethan Raj C, Assistant Professor, Dept. of CSE Page 29

30 Enter data(-1 for no data):3 Enter left child of 3: Enter data(-1 for no data):-1 Enter right child of 3: Enter data(-1 for no data):-1 Enter right child of 8: Enter data(-1 for no data):-1 Enter right child of 7: Enter data(-1 for no data):-1 Enter right child of 5: Enter data(-1 for no data):-1 The preorder traversal of tree is: In the above program, it used preorder traversal that the tree is created properly or not. User can use any other traversal method here. Building Binary Tree from Traversal Pairs: Sometimes it is required to construct a binary tree if its traversals are known. From a single traversal it is not possible to construct unique binary tree. However any of the two traversals are given, then the corresponding tree can be drawn uniquely: 1. Inorder and preorder 2. Inorder and postorder 3. Inorder and level order The basic principle for formulation is as follows: If the preorder traversal is given, then the first node is the root node. If the postorder traversal is given then the last node is the root node. Once the root node is identified, all the nodes in the left sub-trees and right sub-trees of the root node can be identified using inorder. Same technique can be applied repeatedly to form sub-trees. It can be noted that, for the purpose mentioned, two traversal are essential out of which one should be inorder traversal and another preorder or postorder; alternatively, given preorder and postorder traversals, binary tree cannot be obtained uniquely. Example 1: Construct a binary tree from a given preorder and inorder sequence: Preorder: A B D G C E H I F Inorder: D G B A H E I C F Solution: Chethan Raj C, Assistant Professor, Dept. of CSE Page 30

31 From Preorder sequence A B D G C E H I F, the root is: A From Inorder sequence D G B A H E I C F, we get the left and right sub trees: Left sub tree is: D G B Right sub tree is: H E I C F A DGB HEICF To find the root, left and right sub trees for D G B: From the preorder sequence B D G, the root of tree is: B From the inorder sequence D G B, we can find that D and G are to the left of B. The Binary tree upto this point looks like: A B HEICF DG To find the root, left and right sub trees for D G: From the preorder sequence D G, the root of the tree is: D From the inorder sequence D G, we can find that there is no left node to D and G is at the right of D. The Binary tree upto this point looks like A B HEICF D G To find the root, left and right sub trees for H E I C F: From the preorder sequence C E H I F, the root of the left sub tree is: C From the inorder sequence H E I C F, we can find that H E I are at the left of C and F is at the right of C. The Binary tree upto this point looks like: Chethan Raj C, Assistant Professor, Dept. of CSE Page 31

32 A B C D HEI F G To find the root, left and right sub trees for H E I: From the preorder sequence E H I, the root of the tree is: E From the inorder sequence H E I, we can find that H is at the left of E and I is at the right of E. The Binary tree upto this point looks like: Note; Refer class notes for other examples Threaded binary trees A binary tree is represented using array representation or linked list representation. When a binary tree is represented using linked list representation, if any node is not having a child we use NULL pointer in that position. In any binary tree linked list representation, there are more number of NULL pointer than actual pointers. Generally, in any binary tree linked list representation, if there are 2N number of reference fields, then N+1 number of reference fields are filled with NULL ( N+1 are NULL out of 2N). This NULL pointer does not play any role except indicating there is no link (no child). A. J. Perlis and C. Thornton have proposed new binary tree called "Threaded Binary Tree", which make use of NULL pointer to improve its traversal processes. In threaded binary tree, NULL pointers are replaced by references to other nodes in the tree, called threads. Threaded Binary Tree is also a binary tree in which all left child pointers that are NULL (in Linked list representation) points to its in-order predecessor, and all right child pointers that are NULL (in Linked list representation) points to its in-order successor. If there is no in-order predecessor or in-order successor, then it point to root node. Consider the following binary tree. Chethan Raj C, Assistant Professor, Dept. of CSE Page 32

33 To convert above binary tree into threaded binary tree, first find the in-order traversal of that tree... In-order traversal of above binary tree: H - D - I - B - E - A - F - J - C - G When we represent above binary tree using linked list representation, nodes H, I, E, F, J and G left child pointers are NULL. This NULL is replaced by address of its in-order predecessor, respectively (I to D, E to B, F to A, J to F and G to C), but here the node H does not have its in-order predecessor, so it points to the root node A. And nodes H, I, E, J and G right child pointers are NULL. This NULL ponters are replaced by address of its in-order successor, respectively (H to D, I to B, E to A, and J to C), but here the node G does not have its in-order successor, so it points to the root node A. Above example binary tree become as follows after converting into threaded binary tree. In above figure threads are indicated with dotted links. Threaded Binary Tree In the linked list representation of a binary tree T, approximately half of the entries inleft pointer field and right pointer field contains NULL elements. This space occupied by NULL entries can be efficiently utilized to store some kind of valuable information. Thesespecial pointers are called threads, and the binary tree having such pointers is called athreaded binary tree Inorder traversal of a Binary tree can either be done using recursion or with the use of a auxiliary stack. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. A binary tree is made threaded by making all right child pointers that would normally be NULL point to the inorder successor of the node (if it exists). Ex: In a binary search tree, there are many nodes that have an empty left child or empty right child or both. User can utilize these fields in such a way so that the empty left child of a node points to its inorder predecessor and empty right child of the node points to its inorder successor. Chethan Raj C, Assistant Professor, Dept. of CSE Page 33

34 Types of threaded binary trees: Single Threaded: each node is threaded towards either the in-order predecessor or successor (left orright) means all right null pointers will point to inorder successor OR all left null pointers will point to inorder predecessor. Single Threaded: Where a NULL right pointers is made to point to the inorder successor (if successor exists). Or One way threading:- A thread will appear in a right field of a node and will point to the next node in the inorder traversal. Ex: 1. The empty left child field of a node can be used to point to its inorder predecessor. 2. Similarly, the empty right child field of a node can be used to point to its in-order successor One Way Threaded Binary Trees 3. Such a type of binary tree is known as a one way threaded binary tree. 4. A field that holds the address of its in-order successor is known as thread. 5. In-order : Double threaded: The each node is threaded towards both the in-order predecessor and successor (left andright) means all right null pointers will point to inorder successor AND all left null pointers will point to inorder predecessor. Where both left and right NULL pointers are made to point to inorder predecessor and inorder successor respectively. The predecessor threads are useful for reverse inorder traversal and postorder traversal. The threads are also useful for fast accessing ancestors of a node. Or Two way threading:- A thread will also appear in the left field of a node and will point to the preceding node in the inorder traversal. Following diagram shows an example Single Threaded Binary Tree. The dotted lines represent threads. Chethan Raj C, Assistant Professor, Dept. of CSE Page 34

35 Such a type of binary tree is known as a threaded binary tree. A field that holds the address of its inorder successor or predecessor is known as thread. The empty left child field of a node can be used to point to its inorder predecessor. Similarly, the empty right child field of a node can be used to point to its inorder successor. Inorder : Node 30 does not have an inorder predecessor because it is the first node to be traversed in inorder sequence. Similarly, node 80 does not have an inorder successor. Fig: Single and Double threaded binary tree (1) Chethan Raj C, Assistant Professor, Dept. of CSE Page 35

36 Two way Threaded Binary Trees with header Node The right child of the header node always points to itself, Therefore, user take a dummy node called the header node. The threaded binary tree is represented as the left child of the header node. The left thread of node 30 and the right thread of node 80 point to the header node. Representing a Threaded Binary Tree The structure of a node in a threaded binary tree is a bit different from that of a normal binary tree. Unlike a normal binary tree, each node of a threaded binary tree contains two extra pieces of information, namely left thread and right thread Chethan Raj C, Assistant Professor, Dept. of CSE Page 36

37 The left and right thread fields of a node can have two values: 1: Indicates a normal link to the child node 0: Indicates a thread pointing to the inorder predecessor or inorder successor Note: In a threaded binary tree, the right thread of a node points to its inorder successor and the left thread points to its inorder predecessor Chethan Raj C, Assistant Professor, Dept. of CSE Page 37

38 C representation of a Threaded Node Following is C representation of a single threaded node. struct Node int data; Node *left, *right; bool rightthread; Since right pointer is used for two purposes, the boolean variable rightthread is used to indicate whether right pointer points to right child or inorder successor. Similarly, user can add leftthread for a double threaded binary tree. Inorder Taversal using Threads Following is C code for inorder traversal in a threaded binary tree to find leftmost node in a tree rooted with n. struct Node* leftmost(struct Node *n) if (n == NULL) return NULL; while (n->left!= NULL) n = n->left; return n; // C code to do inorder traversal in a threaded binary tree void inorder(struct Node *root) struct Node *cur = leftmost(root); while (cur!= NULL) printf("%d ", cur->data); // If this node is a thread node, then go to // inorder successor if (cur->rightthread) cur = cur->rightthread; else // Else go to the leftmost child in right subtree cur = leftmost(cur->right); Following diagram demonstrates inorder order traversal using threads. Chethan Raj C, Assistant Professor, Dept. of CSE Page 38

39 The binary tree is threaded by making all right child pointers that would normally be null point to the inorder successor of the node (if it exists), and all left child pointers that would normally be null point to the inorder predecessor of the node. We have the pointers reference the next node in an inorder traversal; called threads We need to know if a pointer is an actual link or a thread, so we keep a boolean for each pointer Why do we need Threaded Binary Tree. Binary trees have a lot of wasted space: the leaf nodes each have 2 null pointers. We can use these pointers to help us in inorder traversals. Threaded binary tree makes the tree traversal faster since we do not need stack or recursion for traversal Chethan Raj C, Assistant Professor, Dept. of CSE Page 39

40 Advantage 1. By doing threading user neglect the recursive method of traversing a Tree, which makes use of stack and consumes many memory and time. 2. The node can keep record of its root. Disadvantage 1. This makes the Tree more difficult. 2. More prone to errors when both the child are not present & both values of nodes pointer to their ansentors. APPLICATIONS/USES 1. In the linked representation of a binary tree, additional space is required to store the two links of each node. 2. For leaf nodes, these fields always have nil values as there are no left or right sub-trees present. 3. To remove this drawback of memory wastage, the concept of threaded binary tree was developed. in this type of tree, the empty links are replaced by pointers, called threads which point to some other node of the tree. 4. Threaded trees make in-order tree traversal a little faster without the use of stack or recursion. 5. Threaded binary trees differ from other binary trees in that the null pointers to nonexistent left and right child nodes are used as "threads" to point to prior and successor nodes in the tree.convert a Binary Tree to Threaded binary tree 6. The concept of Threaded Binary Tree is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Where-ever a right pointer is NULL, it is used to store inorder successor. Following diagram shows an example Single Threaded Binary Tree. The dotted lines represent threads. Following is structure of single threaded binary tree. struct Node int key; Node *left, *right; // Used to indicate whether the right pointer is a normal right Chethan Raj C, Assistant Professor, Dept. of CSE Page 40

41 // pointer or a pointer to inorder successor. bool isthreaded; ; How to convert a Given Binary Tree to Threaded Binary Tree The concept is based on the fact that we link from inorder predecessor to a node. We link those inorder predecessor which lie in subtree of node. So we find inorder predecessor of a node if its left is not NULL. Inorder predecessor of a node (whose left is NULL) is rightmost node in left child. Once we find the predecessor, we link a thread from it to current node. Following is the implementation of the above idea. // C++ program to convert a Binary Tree to Threaded Tree #include <iostream> #include <queue> using namespace std; /* Structure of a node in threaded binary tree */ struct Node int key; Node *left, *right; // Used to indicate whether the right pointer // is a normal right pointer or a pointer // to inorder successor. bool isthreaded; ; /*Converts tree with given root to threaded binary tree, This function returns rightmost child of root*/ Node *createthreaded(node *root) // Base cases : Tree is empty or has single // node if (root == NULL) return NULL; if (root->left == NULL && root->right == NULL) return root; // Find predecessor if it exists if (root->left!= NULL) // Find predecessor of root (Rightmost // child in left subtree) Node* l = createthreaded(root->left); // Link a thread from predecessor to // root. l->right = root; l->isthreaded = true; Chethan Raj C, Assistant Professor, Dept. of CSE Page 41

42 // If current node is rightmost child if (root->right == NULL) return root; // Recur for right subtree. return createthreaded(root->right); /* function to find leftmost node in a binary tree rooted with 'root'.this function is used in inorder() */ Node *leftmost(node *root) while (root!= NULL && root->left!= NULL) root = root->left; return root; // Function to do inorder traversal of a threadded // binary tree void inorder(node *root) if (root == NULL) return; // Find the leftmost node in Binary Tree Node *cur = leftmost(root); while (cur!= NULL) cout << cur->key << " "; // If this Node is a thread Node, then go to // inorder successor if (cur->isthreaded) cur = cur->right; else // Else go to the leftmost child in right subtree cur = leftmost(cur->right); // function to create a new node Node *newnode(int key) Node *temp = new Node; temp->left = temp->right = NULL; temp->key = key; return temp; int main() Chethan Raj C, Assistant Professor, Dept. of CSE Page 42

43 /* 1 / \ 2 3 / \ / \ */ Node *root = newnode(1); root->left = newnode(2); root->right = newnode(3); root->left->left = newnode(4); root->left->right = newnode(5); root->right->left = newnode(6); root->right->right = newnode(7); createthreaded(root); cout << "Inorder traversal of creeated " "threaded tree is\n"; inorder(root); return 0; Output: Inorder traversal of creeated threaded tree is Binary Search Trees In a binary tree, every node can have maximum of two children but there is no order of nodes based on their values. In binary tree, the elements are arranged as they arrive to the tree, from top to bottom and left to right. To enhance the performance of binary tree, we use special type of binary tree known as Binary Search Tree. Binary search tree mainly focus on the search operation in binary tree. Binary search tree can be defined as follows, Binary Search Tree is a binary tree in which every node contains only smaller values in its left subtree and only larger values in its right subtree. The following tree is a Binary Search Tree. In this tree, left subtree of every node contains nodes with smaller values and right subtree of every node contains larger values. Chethan Raj C, Assistant Professor, Dept. of CSE Page 43

44 Every Binary Search Tree is a binary tree but all the Binary Trees need not to be binary search trees. Operations on a Binary Search Tree Binary search tree is a data structure that quickly allows us to maintain a sorted list of numbers. It is called a binary tree because each tree node has maximum of two children. It is called a search tree because it can be used to search for the presence of a number in O(log(n)) time. The following operations are performed on a binary search tree Search 2. Insertion 3. Deletion 4. Traversal Properties The properties that separates a binary search tree from a regular binary tree is All nodes of left subtree are less than root node All nodes of right subtree are more than root node Both subtrees of each node are also BSTs i.e. they have the above two properties. The binary tree on the right isn't a binary search tree because the right subtree of the node "3" contains a value smaller that it. Search Operation in BST In a binary search tree, the search operation is performed with O(log n) time complexity. The search operation is performed as follows. The algorithm depends on the property of BST that if each left subtree has values below root and each right subtree has values above root. If the value is below root, we can say for sure that the value is not in the right subtree; we need to only search in the left subtree and if the value is above root, we can say for sure that the value is not in the left subtree; we need to only search in the right subtree. Chethan Raj C, Assistant Professor, Dept. of CSE Page 44

45 Algorithm: If root == NULL return NULL; If number == root->data return root->data; If number < root->data return search(root->left) If number > root->data return search(root->right) Steps: Step 1: Read the search element from the user Step 2: Compare, the search element with the value of root node in the tree. Step 3: If both are matching, then display "Given node found!!!" and terminate the function Step 4: If both are not matching, then check whether search element is smaller or larger than that node value. Step 5: If search element is smaller, then continue the search process in left subtree. Step 6: If search element is larger, then continue the search process in right subtree. Step 7: Repeat the same until we find exact element or we completed with a leaf node Step 8: If we reach the node with search value, then display "Element is found" and terminate the function. Step 9: If we reach a leaf node and it is also not matching, then display "Element not found" and terminate the function. // C function to search a given key in a given BST struct node* search(struct node* root, int key) // Base Cases: root is null or key is present at root if (root == NULL root->key == key) return root; // Key is greater than root's key if (root->key < key) return search(root->right, key); // Key is smaller than root's key return search(root->left, key); Refer Lab Program 10 to search for an key element in a binary search tree Insertion Operation in BST Inserting a value in the correct position is similar to searching because we try to maintain the rule that left subtree is lesser than root and right subtree is larger than root. Chethan Raj C, Assistant Professor, Dept. of CSE Page 45

46 User keep going to either right subtree or left subtree depending on the value and when we reach a point left or right subtree is null, we put the new node there. Algorithm: If node == NULL return createnode(data) if (data < node->data) node->left = insert(node->left, data); else if (data > node->data) node->right = insert(node->right, data); return node; Steps: In a binary search tree, the insertion operation is performed with O(log n) time complexity. In binary search tree, new node is always inserted as a leaf node. The insertion operation is performed as follows. Step 1: Create a newnode with given value and set its left and right to NULL. Step 2: Check whether tree is Empty. Step 3: If the tree is Empty, then set set root to newnode. Step 4: If the tree is Not Empty, then check whether value of newnode is smaller or larger than the node (here it is root node). Step 5: If newnode 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 to a leaf node (e.i., reach to NULL). Step 7: After reaching a leaf node, then isert the newnode as left child if newnode is smaller or equal to that leaf else insert it as right child. C function struct node* insert(struct node* node, int key) /* If the tree is empty, return a new node */ if (node == NULL) return newnode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node; Refer Lab Program 10 to insert an element into binary search tree Ex: Create a BST and display the nodes by preorder traversal (root, left child, right child). #include<stdio.h> Chethan Raj C, Assistant Professor, Dept. of CSE Page 46

47 #include<stdlib.h> typedef struct BST int data; struct BST *left; struct BST *right; node; node *create(); void insert(node *,node *); void preorder(node *); int main() char ch; node *root=null,*temp; do temp=create(); if(root==null) root=temp; else insert(root,temp); printf("ndo you want to enter more(y/n)?"); getchar(); scanf("%c",&ch); while(ch=='y' ch=='y'); printf("npreorder Traversal: "); preorder(root); return 0; node *create() node *temp; printf("nenter data:"); temp=(node*)malloc(sizeof(node)); scanf("%d",&temp->data); temp->left=temp->right=null; return temp; void insert(node *root,node *temp) if(temp->data<root->data) if(root->left!=null) insert(root->left,temp); else root->left=temp; if(temp->data>root->data) if(root->right!=null) insert(root->right,temp); Chethan Raj C, Assistant Professor, Dept. of CSE Page 47

48 else root->right=temp; void preorder(node *root) if(root!=null) printf("%d ",root->data); preorder(root->left); preorder(root->right); Output Deletion Operation in BST In a binary search tree, the deletion operation is performed with O(log n) time complexity. Deleting a node 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 Case 3: Deleting a node with two children Case 1: Deleting a leaf node We use the following steps to delete a leaf node from BST... Step 1: Find the node to be deleted using search operation Step 2: Delete the node using free function (If it is a leaf) and terminate the function. Case 2: Deleting a node with one child Chethan Raj C, Assistant Professor, Dept. of CSE Page 48

49 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. Ex: Node to be removed has no children. This case is quite simple. Algorithm sets corresponding link of the parent to NULL and disposes the node. Example. Remove -4 from a BST. Ex: Node to be removed has one child. It this case, node is cut from the tree and algorithm links single child (with it's subtree) directly to the parent of the removed node. Example. Remove 18 from a BST. Chethan Raj C, Assistant Professor, Dept. of CSE Page 49

50 Node to be removed has two children. This is the most complex case. To solve it, let us see one useful BST property first. We are going to use the idea, that the same set of values may be represented as different binary-search trees. For example BST contains the same values 5, 19, 21, 25. To transform first tree into second one, we can do following: choose minimum element from the right subtree (19 in the example); replace 5 by 19; hang 5 as a left child. The same approach can be utilized to remove a node, which has two children: find a minimum value in the right subtree; replace value of the node to be removed with found minimum. Now, right subtree contains a duplicate! apply remove to the right subtree to remove a duplicate. Notice, that the node with minimum value has no left child and, therefore, it's removal may result in first or second cases only. Example. Remove 12 from a BST. Example. Remove 12 from a BST. Chethan Raj C, Assistant Professor, Dept. of CSE Page 50

51 Find minimum element in the right subtree of the node to be removed. In current example it is 19. Replace 12 with 19. Notice, that only values are replaced, not nodes. Now we have two nodes with the same value. Remove 19 from the left subtree. Program to Construct a Binary Search Tree and perform deletion, inorder traversal on it #include <stdio.h> #include <stdlib.h> struct btnode int value; struct btnode *l; struct btnode *r; *root = NULL, *temp = NULL, *t2, *t1; Chethan Raj C, Assistant Professor, Dept. of CSE Page 51

52 void delete1(); void insert(); void delete(); void inorder(struct btnode *t); void create(); void search(struct btnode *t); void preorder(struct btnode *t); void postorder(struct btnode *t); void search1(struct btnode *t,int data); int smallest(struct btnode *t); int largest(struct btnode *t); int flag = 1; void main() int ch; printf("\noperations ---"); printf("\n1 - Insert an element into tree\n"); printf("2 - Delete an element from the tree\n"); printf("3 - Inorder Traversal\n"); printf("4 - Preorder Traversal\n"); printf("5 - Postorder Traversal\n"); printf("6 - Exit\n"); while(1) printf("\nenter your choice : "); scanf("%d", &ch); switch (ch) case 1: insert(); break; case 2: delete(); break; case 3: inorder(root); break; case 4: preorder(root); break; case 5: postorder(root); break; case 6: exit(0); default : printf("wrong choice, Please enter correct choice "); break; Chethan Raj C, Assistant Professor, Dept. of CSE Page 52

53 /* To insert a node in the tree */ void insert() create(); if (root == NULL) root = temp; else search(root); /* To create a node */ void create() int data; printf("enter data of node to be inserted : "); scanf("%d", &data); temp = (struct btnode *)malloc(1*sizeof(struct btnode)); temp->value = data; temp->l = temp->r = NULL; /* Function to search the appropriate position to insert the new node */ void search(struct btnode *t) if ((temp->value > t->value) && (t->r!= NULL)) /* value more than root node value insert at right */ search(t->r); else if ((temp->value > t->value) && (t->r == NULL)) t->r = temp; else if ((temp->value < t->value) && (t->l!= NULL)) /* value less than root node value insert at left */ search(t->l); else if ((temp->value < t->value) && (t->l == NULL)) t->l = temp; /* recursive function to perform inorder traversal of tree */ void inorder(struct btnode *t) if (root == NULL) printf("no elements in a tree to display"); return; if (t->l!= NULL) inorder(t->l); printf("%d -> ", t->value); if (t->r!= NULL) inorder(t->r); /* To check for the deleted node */ void delete() int data; Chethan Raj C, Assistant Professor, Dept. of CSE Page 53

54 if (root == NULL) printf("no elements in a tree to delete"); return; printf("enter the data to be deleted : "); scanf("%d", &data); t1 = root; t2 = root; search1(root, data); /* To find the preorder traversal */ void preorder(struct btnode *t) if (root == NULL) printf("no elements in a tree to display"); return; printf("%d -> ", t->value); if (t->l!= NULL) preorder(t->l); if (t->r!= NULL) preorder(t->r); /* To find the postorder traversal */ void postorder(struct btnode *t) if (root == NULL) printf("no elements in a tree to display "); return; if (t->l!= NULL) postorder(t->l); if (t->r!= NULL) postorder(t->r); printf("%d -> ", t->value); /* Search for the appropriate position to insert the new node */ void search1(struct btnode *t, int data) if ((data>t->value)) t1 = t; search1(t->r, data); else if ((data < t->value)) t1 = t; search1(t->l, data); Chethan Raj C, Assistant Professor, Dept. of CSE Page 54

55 else if ((data==t->value)) delete1(t); /* To delete a node */ void delete1(struct btnode *t) int k; /* To delete leaf node */ if ((t->l == NULL) && (t->r == NULL)) if (t1->l == t) t1->l = NULL; else t1->r = NULL; t = NULL; free(t); return; /* To delete node having one left hand child */ else if ((t->r == NULL)) if (t1 == t) root = t->l; t1 = root; else if (t1->l == t) t1->l = t->l; else t1->r = t->l; t = NULL; free(t); return; /* To delete node having right hand child */ else if (t->l == NULL) if (t1 == t) root = t->r; Chethan Raj C, Assistant Professor, Dept. of CSE Page 55

56 t1 = root; else if (t1->r == t) t1->r = t->r; else t1->l = t->r; t == NULL; free(t); return; /* To delete node having two child */ else if ((t->l!= NULL) && (t->r!= NULL)) t2 = root; if (t->r!= NULL) k = smallest(t->r); flag = 1; else k =largest(t->l); flag = 2; search1(root, k); t->value = k; /* To find the smallest element in the right sub tree */ int smallest(struct btnode *t) t2 = t; if (t->l!= NULL) t2 = t; return(smallest(t->l)); else return (t->value); /* To find the largest element in the left sub tree */ int largest(struct btnode *t) if (t->r!= NULL) t2 = t; return(largest(t->r)); else return(t->value); Chethan Raj C, Assistant Professor, Dept. of CSE Page 56

57 $ cc tree43.c $ a.out Output Insert an element into tree 2 - Delete an element from the tree 3 - Inorder Traversal 4 - Preorder Traversal 5 - Postorder Traversal 6 - Exit Enter your choice : 1 Enter data of node to be inserted : 40 Enter your choice : 1 Enter data of node to be inserted : 20 Enter your choice : 1 Enter data of node to be inserted : 10 Enter your choice : 1 Enter data of node to be inserted : 30 Enter your choice : 1 Enter data of node to be inserted : 60 Enter your choice : 1 Enter data of node to be inserted : 80 Enter your choice : 1 Enter data of node to be inserted : 90 Enter your choice : > 20 -> 30 -> 40 -> 60 -> 80 -> 90 -> Construct a Binary Search Tree for the following sequence of numbers 10,12,5,4,20,8,7,15 and 13 Refer notes for examples and implementation Applications of BST: 1) Handling Duplicates: Increment a counter stored in item s node 2) Use a linked list or another search tree at item s node 3) Application: Look-up table. 4) BST is used as a data structure for rapid access to store data in sorted form and search stored elements quickly. 5) It can be used to represent arithmetic expressions i.e called expression tree. 6) BST used in Unix kernels for managing a set of virtual memory areas Chethan Raj C, Assistant Professor, Dept. of CSE Page 57

58 Expression Trees: A Expression Tree is a special kind of binary tree in which: 1. Each leaf node contains a single operand 2. Each nonleaf node contains a single binary operator 3. The left and right subtrees of an operator node represent subexpressions that must be evaluated before applying the operator at the root of the subtree. Binary Expression Tree: (4+2)*3=18 Levels Indicate Precedence The levels of the nodes in the tree indicate their relative precedence of evaluation (we do not need parentheses to indicate precedence). Operations at higher levels of the tree are evaluated later than those below them. The operation at the root is always the last operation performed. Example Arithmetic Expression: A + (B * (C / D) ) Tree for the above expression: Leaves = operands (constants/variables) Non-leaf nodes = operators Example: Representing Arithmetic Expressions 1. The levels of the nodes in the tree indicate their relative precedence of evaluation (User do not need parentheses to indicate precedence). 2. Operations at lower levels of the tree are evaluated later than those at higher levels. Chethan Raj C, Assistant Professor, Dept. of CSE Page 58

59 3. The operation at the root is always the last operation performed. Applications of expression tree: Used in most compilers No parenthesis need use tree structure Can speed up calculations e.g. replace / node with C/D if C and D are known Evaluating Arithmetic Expression Trees 1. Recursively evaluate left and right subtrees 2. Apply operation at the root Known as Postorder traversal Process children first and then the root (therefore post order) Traversing Trees Postorder: Children first, then Root A B C D / * + Preorder: Root, then Children + A * B / C D Inorder: Left child, Root, Right child A + B * C / D Chethan Raj C, Assistant Professor, Dept. of CSE Page 59

Binary Trees. Height 1

Binary Trees. Height 1 Binary Trees Definitions A tree is a finite set of one or more nodes that shows parent-child relationship such that There is a special node called root Remaining nodes are portioned into subsets T1,T2,T3.

More information

[ DATA STRUCTURES ] Fig. (1) : A Tree

[ DATA STRUCTURES ] Fig. (1) : A Tree [ DATA STRUCTURES ] Chapter - 07 : Trees 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 amongst several

More information

Data Structure - Binary Tree 1 -

Data Structure - Binary Tree 1 - Data Structure - Binary Tree 1 - Hanyang University Jong-Il Park Basic Tree Concepts Logical structures Chap. 2~4 Chap. 5 Chap. 6 Linear list Tree Graph Linear structures Non-linear structures Linear Lists

More information

6-TREE. Tree: Directed Tree: A directed tree is an acyclic digraph which has one node called the root node

6-TREE. Tree: Directed Tree: A directed tree is an acyclic digraph which has one node called the root node 6-TREE Data Structure Management (330701) Tree: A tree is defined as a finite set of one or more nodes such that There is a special node called the root node R. The remaining nodes are divided into n 0

More information

TREES. Trees - Introduction

TREES. Trees - Introduction TREES Chapter 6 Trees - Introduction All previous data organizations we've studied are linear each element can have only one predecessor and successor Accessing all elements in a linear sequence is O(n)

More information

Trees CONTENTS. Hours: 8. Marks: 12. Anuradha Bhatia 1

Trees CONTENTS. Hours: 8. Marks: 12. Anuradha Bhatia 1 Trees CONTENTS 6.1 Introduction 1. Terminologies: tree,degree of a node, degree of a tree, level of a node, leaf node, Depth / Height of a tree, In-degree & out- Degree, Directed edge, Path, Ancestor &

More information

A set of nodes (or vertices) with a single starting point

A set of nodes (or vertices) with a single starting point Binary Search Trees Understand tree terminology Understand and implement tree traversals Define the binary search tree property Implement binary search trees Implement the TreeSort algorithm 2 A set of

More information

Binary Trees, Binary Search Trees

Binary Trees, Binary Search Trees Binary Trees, Binary Search Trees Trees Linear access time of linked lists is prohibitive Does there exist any simple data structure for which the running time of most operations (search, insert, delete)

More information

Trees. (Trees) Data Structures and Programming Spring / 28

Trees. (Trees) Data Structures and Programming Spring / 28 Trees (Trees) Data Structures and Programming Spring 2018 1 / 28 Trees A tree is a collection of nodes, which can be empty (recursive definition) If not empty, a tree consists of a distinguished node r

More information

Tree Data Structures CSC 221

Tree Data Structures CSC 221 Tree Data Structures CSC 221 Specialized Trees Binary Tree: A restriction of trees such that the maximum degree of a node is 2. Order of nodes is now relevant May have zero nodes (emtpy tree) Formal Definition:

More information

Binary Trees. Examples:

Binary Trees. Examples: Binary Trees A tree is a data structure that is made of nodes and pointers, much like a linked list. The difference between them lies in how they are organized: In a linked list each node is connected

More information

Binary Trees

Binary Trees Binary Trees 4-7-2005 Opening Discussion What did we talk about last class? Do you have any code to show? Do you have any questions about the assignment? What is a Tree? You are all familiar with what

More information

Trees. Introduction & Terminology. February 05, 2018 Cinda Heeren / Geoffrey Tien 1

Trees. Introduction & Terminology. February 05, 2018 Cinda Heeren / Geoffrey Tien 1 Trees Introduction & Terminology Cinda Heeren / Geoffrey Tien 1 Review: linked lists Linked lists are constructed out of nodes, consisting of a data element a pointer to another node Lists are constructed

More information

Data and File Structures Laboratory

Data and File Structures Laboratory Binary Trees Assistant Professor Machine Intelligence Unit Indian Statistical Institute, Kolkata September, 2018 1 Basics 2 Implementation 3 Traversal Basics of a tree A tree is recursively defined as

More information

Bioinformatics Programming. EE, NCKU Tien-Hao Chang (Darby Chang)

Bioinformatics Programming. EE, NCKU Tien-Hao Chang (Darby Chang) Bioinformatics Programming EE, NCKU Tien-Hao Chang (Darby Chang) 1 Tree 2 A Tree Structure A tree structure means that the data are organized so that items of information are related by branches 3 Definition

More information

UNIT IV -NON-LINEAR DATA STRUCTURES 4.1 Trees TREE: A tree is a finite set of one or more nodes such that there is a specially designated node called the Root, and zero or more non empty sub trees T1,

More information

8. Write an example for expression tree. [A/M 10] (A+B)*((C-D)/(E^F))

8. Write an example for expression tree. [A/M 10] (A+B)*((C-D)/(E^F)) DHANALAKSHMI COLLEGE OF ENGINEERING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING EC6301 OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES UNIT IV NONLINEAR DATA STRUCTURES Part A 1. Define Tree [N/D 08]

More information

Chapter 20: Binary Trees

Chapter 20: Binary Trees Chapter 20: Binary Trees 20.1 Definition and Application of Binary Trees Definition and Application of Binary Trees Binary tree: a nonlinear linked list in which each node may point to 0, 1, or two other

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 11: Binary Search Trees MOUNA KACEM mouna@cs.wisc.edu Fall 2018 General Overview of Data Structures 2 Introduction to trees 3 Tree: Important non-linear data structure

More information

We have the pointers reference the next node in an inorder traversal; called threads

We have the pointers reference the next node in an inorder traversal; called threads Leaning Objective: In this Module you will be learning the following: Threaded Binary Tree Introduction: Threaded Binary Tree is also a binary tree in which all left child pointers that are NULL (in Linked

More information

Tree Structures. Definitions: o A tree is a connected acyclic graph. o A disconnected acyclic graph is called a forest

Tree Structures. Definitions: o A tree is a connected acyclic graph. o A disconnected acyclic graph is called a forest Tree Structures Definitions: o A tree is a connected acyclic graph. o A disconnected acyclic graph is called a forest o A tree is a connected digraph with these properties: There is exactly one node (Root)

More information

CS301 - Data Structures Glossary By

CS301 - Data Structures Glossary By CS301 - Data Structures Glossary By Abstract Data Type : A set of data values and associated operations that are precisely specified independent of any particular implementation. Also known as ADT Algorithm

More information

CE 221 Data Structures and Algorithms

CE 221 Data Structures and Algorithms CE 221 Data Structures and Algorithms Chapter 4: Trees (Binary) Text: Read Weiss, 4.1 4.2 Izmir University of Economics 1 Preliminaries - I (Recursive) Definition: A tree is a collection of nodes. The

More information

BBM 201 Data structures

BBM 201 Data structures BBM 201 Data structures Lecture 11: Trees 2018-2019 Fall Content Terminology The Binary Tree The Binary Search Tree Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, 2013

More information

Binary Trees and Binary Search Trees

Binary Trees and Binary Search Trees Binary Trees and Binary Search Trees Learning Goals After this unit, you should be able to... Determine if a given tree is an instance of a particular type (e.g. binary, and later heap, etc.) Describe

More information

Trees. Truong Tuan Anh CSE-HCMUT

Trees. Truong Tuan Anh CSE-HCMUT Trees Truong Tuan Anh CSE-HCMUT Outline Basic concepts Trees Trees A tree consists of a finite set of elements, called nodes, and a finite set of directed lines, called branches, that connect the nodes

More information

BST Implementation. Data Structures. Lecture 4 Binary search trees (BST) Dr. Mahmoud Attia Sakr University of Ain Shams

BST Implementation. Data Structures. Lecture 4 Binary search trees (BST) Dr. Mahmoud Attia Sakr University of Ain Shams Lecture 4 Binary search trees (BST) Dr. Mahmoud Attia Sakr mahmoud.sakr@cis.asu.edu.eg Cairo, Egypt, October 2012 Binary Search Trees (BST) 1. Hierarchical data structure with a single reference to root

More information

March 20/2003 Jayakanth Srinivasan,

March 20/2003 Jayakanth Srinivasan, Definition : A simple graph G = (V, E) consists of V, a nonempty set of vertices, and E, a set of unordered pairs of distinct elements of V called edges. Definition : In a multigraph G = (V, E) two or

More information

Data Structure. IBPS SO (IT- Officer) Exam 2017

Data Structure. IBPS SO (IT- Officer) Exam 2017 Data Structure IBPS SO (IT- Officer) Exam 2017 Data Structure: In computer science, a data structure is a way of storing and organizing data in a computer s memory so that it can be used efficiently. Data

More information

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

Advanced Java Concepts Unit 5: Trees. Notes and Exercises Advanced Java Concepts Unit 5: Trees. Notes and Exercises A Tree is a data structure like the figure shown below. We don t usually care about unordered trees but that s where we ll start. Later we will

More information

Computer Science 210 Data Structures Siena College Fall Topic Notes: Trees

Computer Science 210 Data Structures Siena College Fall Topic Notes: Trees Computer Science 0 Data Structures Siena College Fall 08 Topic Notes: Trees We ve spent a lot of time looking at a variety of structures where there is a natural linear ordering of the elements in arrays,

More information

Discussion 2C Notes (Week 8, February 25) TA: Brian Choi Section Webpage:

Discussion 2C Notes (Week 8, February 25) TA: Brian Choi Section Webpage: Discussion 2C Notes (Week 8, February 25) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs32 Trees Definitions Yet another data structure -- trees. Just like a linked

More information

Stacks, Queues and Hierarchical Collections

Stacks, Queues and Hierarchical Collections Programming III Stacks, Queues and Hierarchical Collections 2501ICT Nathan Contents Linked Data Structures Revisited Stacks Queues Trees Binary Trees Generic Trees Implementations 2 Copyright 2002- by

More information

Stacks, Queues and Hierarchical Collections. 2501ICT Logan

Stacks, Queues and Hierarchical Collections. 2501ICT Logan Stacks, Queues and Hierarchical Collections 2501ICT Logan Contents Linked Data Structures Revisited Stacks Queues Trees Binary Trees Generic Trees Implementations 2 Queues and Stacks Queues and Stacks

More information

Lecture Notes 16 - Trees CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson

Lecture Notes 16 - Trees CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson Lecture Notes 16 - Trees CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson Reading: Carrano, Chapter 15 Introduction to trees The data structures we have seen so far to implement

More information

Trees. CSE 373 Data Structures

Trees. CSE 373 Data Structures Trees CSE 373 Data Structures Readings Reading Chapter 7 Trees 2 Why Do We Need Trees? Lists, Stacks, and Queues are linear relationships Information often contains hierarchical relationships File directories

More information

Tree Structures. A hierarchical data structure whose point of entry is the root node

Tree Structures. A hierarchical data structure whose point of entry is the root node Binary Trees 1 Tree Structures A tree is A hierarchical data structure whose point of entry is the root node This structure can be partitioned into disjoint subsets These subsets are themselves trees and

More information

Trees. Q: Why study trees? A: Many advance ADTs are implemented using tree-based data structures.

Trees. Q: Why study trees? A: Many advance ADTs are implemented using tree-based data structures. Trees Q: Why study trees? : Many advance DTs are implemented using tree-based data structures. Recursive Definition of (Rooted) Tree: Let T be a set with n 0 elements. (i) If n = 0, T is an empty tree,

More information

DATA STRUCTURE : A MCQ QUESTION SET Code : RBMCQ0305

DATA STRUCTURE : A MCQ QUESTION SET Code : RBMCQ0305 Q.1 If h is any hashing function and is used to hash n keys in to a table of size m, where n

More information

CSE 230 Intermediate Programming in C and C++ Binary Tree

CSE 230 Intermediate Programming in C and C++ Binary Tree CSE 230 Intermediate Programming in C and C++ Binary Tree Fall 2017 Stony Brook University Instructor: Shebuti Rayana shebuti.rayana@stonybrook.edu Introduction to Tree Tree is a non-linear data structure

More information

Garbage Collection: recycling unused memory

Garbage Collection: recycling unused memory Outline backtracking garbage collection trees binary search trees tree traversal binary search tree algorithms: add, remove, traverse binary node class 1 Backtracking finding a path through a maze is an

More information

Algorithms and Data Structures (INF1) Lecture 8/15 Hua Lu

Algorithms and Data Structures (INF1) Lecture 8/15 Hua Lu Algorithms and Data Structures (INF1) Lecture 8/15 Hua Lu Department of Computer Science Aalborg University Fall 2007 This Lecture Trees Basics Rooted trees Binary trees Binary tree ADT Tree traversal

More information

Unit III - Tree TREES

Unit III - Tree TREES TREES Unit III - Tree Consider a scenario where you are required to represent the directory structure of your operating system. The directory structure contains various folders and files. A folder may

More information

CHAPTER 5. Trees CHAPTER 5 1/70

CHAPTER 5. Trees CHAPTER 5 1/70 CHAPTER 5 Trees All the programs in this file are selected from Ellis Horowitz, Sartaj Sahni, and Susan Anderson-Freed Fundamentals of Data Structures in C /2nd Edition, Silicon Press, 2008. CHAPTER 5

More information

Introduction to Computers and Programming. Concept Question

Introduction to Computers and Programming. Concept Question Introduction to Computers and Programming Prof. I. K. Lundqvist Lecture 7 April 2 2004 Concept Question G1(V1,E1) A graph G(V, where E) is V1 a finite = {}, nonempty E1 = {} set of G2(V2,E2) vertices and

More information

CSCI-401 Examlet #5. Name: Class: Date: True/False Indicate whether the sentence or statement is true or false.

CSCI-401 Examlet #5. Name: Class: Date: True/False Indicate whether the sentence or statement is true or false. Name: Class: Date: CSCI-401 Examlet #5 True/False Indicate whether the sentence or statement is true or false. 1. The root node of the standard binary tree can be drawn anywhere in the tree diagram. 2.

More information

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs Computational Optimization ISE 407 Lecture 16 Dr. Ted Ralphs ISE 407 Lecture 16 1 References for Today s Lecture Required reading Sections 6.5-6.7 References CLRS Chapter 22 R. Sedgewick, Algorithms in

More information

Trees : Part 1. Section 4.1. Theory and Terminology. A Tree? A Tree? Theory and Terminology. Theory and Terminology

Trees : Part 1. Section 4.1. Theory and Terminology. A Tree? A Tree? Theory and Terminology. Theory and Terminology Trees : Part Section. () (2) Preorder, Postorder and Levelorder Traversals Definition: A tree is a connected graph with no cycles Consequences: Between any two vertices, there is exactly one unique path

More information

CSE 250 Final Exam. Fall 2013 Time: 3 hours. Dec 11, No electronic devices of any kind. You can open your textbook and notes

CSE 250 Final Exam. Fall 2013 Time: 3 hours. Dec 11, No electronic devices of any kind. You can open your textbook and notes CSE 250 Final Exam Fall 2013 Time: 3 hours. Dec 11, 2013 Total points: 100 14 pages Please use the space provided for each question, and the back of the page if you need to. Please do not use any extra

More information

CS24 Week 8 Lecture 1

CS24 Week 8 Lecture 1 CS24 Week 8 Lecture 1 Kyle Dewey Overview Tree terminology Tree traversals Implementation (if time) Terminology Node The most basic component of a tree - the squares Edge The connections between nodes

More information

12 Abstract Data Types

12 Abstract Data Types 12 Abstract Data Types 12.1 Foundations of Computer Science Cengage Learning Objectives After studying this chapter, the student should be able to: Define the concept of an abstract data type (ADT). Define

More information

Principles of Computer Science

Principles of Computer Science Principles of Computer Science Binary Trees 08/11/2013 CSCI 2010 - Binary Trees - F.Z. Qureshi 1 Today s Topics Extending LinkedList with Fast Search Sorted Binary Trees Tree Concepts Traversals of a Binary

More information

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE TED (10)-3071 Reg. No.. (REVISION-2010) Signature. FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours (Maximum marks: 100)

More information

Trees! Ellen Walker! CPSC 201 Data Structures! Hiram College!

Trees! Ellen Walker! CPSC 201 Data Structures! Hiram College! Trees! Ellen Walker! CPSC 201 Data Structures! Hiram College! ADTʼs Weʼve Studied! Position-oriented ADT! List! Stack! Queue! Value-oriented ADT! Sorted list! All of these are linear! One previous item;

More information

First Semester - Question Bank Department of Computer Science Advanced Data Structures and Algorithms...

First Semester - Question Bank Department of Computer Science Advanced Data Structures and Algorithms... First Semester - Question Bank Department of Computer Science Advanced Data Structures and Algorithms.... Q1) What are some of the applications for the tree data structure? Q2) There are 8, 15, 13, and

More information

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the elements may locate at far positions

More information

Section 5.5. Left subtree The left subtree of a vertex V on a binary tree is the graph formed by the left child L of V, the descendents

Section 5.5. Left subtree The left subtree of a vertex V on a binary tree is the graph formed by the left child L of V, the descendents Section 5.5 Binary Tree A binary tree is a rooted tree in which each vertex has at most two children and each child is designated as being a left child or a right child. Thus, in a binary tree, each vertex

More information

Binary Tree. Preview. Binary Tree. Binary Tree. Binary Search Tree 10/2/2017. Binary Tree

Binary Tree. Preview. Binary Tree. Binary Tree. Binary Search Tree 10/2/2017. Binary Tree 0/2/ Preview Binary Tree Tree Binary Tree Property functions In-order walk Pre-order walk Post-order walk Search Tree Insert an element to the Tree Delete an element form the Tree A binary tree is a tree

More information

Definition of Graphs and Trees. Representation of Trees.

Definition of Graphs and Trees. Representation of Trees. Definition of Graphs and Trees. Representation of Trees. Chapter 6 Definition of graphs (I) A directed graph or digraph is a pair G = (V,E) s.t.: V is a finite set called the set of vertices of G. E V

More information

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text)

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text) Lec 17 April 8 Topics: binary Trees expression trees Binary Search Trees (Chapter 5 of text) Trees Linear access time of linked lists is prohibitive Heap can t support search in O(log N) time. (takes O(N)

More information

a graph is a data structure made up of nodes in graph theory the links are normally called edges

a graph is a data structure made up of nodes in graph theory the links are normally called edges 1 Trees Graphs a graph is a data structure made up of nodes each node stores data each node has links to zero or more nodes in graph theory the links are normally called edges graphs occur frequently in

More information

CMPT 225. Binary Search Trees

CMPT 225. Binary Search Trees CMPT 225 Binary Search Trees Trees A set of nodes with a single starting point called the root Each node is connected by an edge to some other node A tree is a connected graph There is a path to every

More information

Data Structures Question Bank Multiple Choice

Data Structures Question Bank Multiple Choice Section 1. Fundamentals: Complexity, Algorthm Analysis 1. An algorithm solves A single problem or function Multiple problems or functions Has a single programming language implementation 2. A solution

More information

Tree. A path is a connected sequence of edges. A tree topology is acyclic there is no loop.

Tree. A path is a connected sequence of edges. A tree topology is acyclic there is no loop. Tree A tree consists of a set of nodes and a set of edges connecting pairs of nodes. A tree has the property that there is exactly one path (no more, no less) between any pair of nodes. A path is a connected

More information

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified) WINTER 18 EXAMINATION Subject Name: Data Structure using C Model wer Subject Code: 22317 Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given

More information

Why Do We Need Trees?

Why Do We Need Trees? CSE 373 Lecture 6: Trees Today s agenda: Trees: Definition and terminology Traversing trees Binary search trees Inserting into and deleting from trees Covered in Chapter 4 of the text Why Do We Need Trees?

More information

Data Structures. Trees. By Dr. Mohammad Ali H. Eljinini. M.A. Eljinini, PhD

Data Structures. Trees. By Dr. Mohammad Ali H. Eljinini. M.A. Eljinini, PhD Data Structures Trees By Dr. Mohammad Ali H. Eljinini Trees Are collections of items arranged in a tree like data structure (none linear). Items are stored inside units called nodes. However: We can use

More information

Trees. A tree is a directed graph with the property

Trees. A tree is a directed graph with the property 2: Trees Trees A tree is a directed graph with the property There is one node (the root) from which all other nodes can be reached by exactly one path. Seen lots of examples. Parse Trees Decision Trees

More information

CSCI2100B Data Structures Trees

CSCI2100B Data Structures Trees CSCI2100B Data Structures Trees Irwin King king@cse.cuhk.edu.hk http://www.cse.cuhk.edu.hk/~king Department of Computer Science & Engineering The Chinese University of Hong Kong Introduction General Tree

More information

Algorithms and Data Structures

Algorithms and Data Structures Lesson 3: trees and visits Luciano Bononi http://www.cs.unibo.it/~bononi/ (slide credits: these slides are a revised version of slides created by Dr. Gabriele D Angelo) International

More information

Solution to CSE 250 Final Exam

Solution to CSE 250 Final Exam Solution to CSE 250 Final Exam Fall 2013 Time: 3 hours. December 13, 2013 Total points: 100 14 pages Please use the space provided for each question, and the back of the page if you need to. Please do

More information

Graphs V={A,B,C,D,E} E={ (A,D),(A,E),(B,D), (B,E),(C,D),(C,E)}

Graphs V={A,B,C,D,E} E={ (A,D),(A,E),(B,D), (B,E),(C,D),(C,E)} Graphs and Trees 1 Graphs (simple) graph G = (V, ) consists of V, a nonempty set of vertices and, a set of unordered pairs of distinct vertices called edges. xamples V={,,,,} ={ (,),(,),(,), (,),(,),(,)}

More information

DATA STRUCTURES USING C

DATA STRUCTURES USING C DATA STRUCTURES USING C The British Constitution Crown Church of England Cabinet House of Commons House of Lords Supreme Court Ministers County Metropolitan Council police Rural District County Borough

More information

Topic 14. The BinaryTree ADT

Topic 14. The BinaryTree ADT Topic 14 The BinaryTree ADT Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary tree implementation Examine a binary tree

More information

CSCI212 Computer Science. Binary Trees/Heaps/Binary Search Trees

CSCI212 Computer Science. Binary Trees/Heaps/Binary Search Trees CSCI212 Computer Science Binary Trees/Heaps/Binary Search Trees Tree Terminology 0 A tree is a non-linear abstract data type that stores elements hierarchically. 0 With the exception of the top element

More information

CS8391-DATA STRUCTURES QUESTION BANK UNIT I

CS8391-DATA STRUCTURES QUESTION BANK UNIT I CS8391-DATA STRUCTURES QUESTION BANK UNIT I 2MARKS 1.Define data structure. The data structure can be defined as the collection of elements and all the possible operations which are required for those

More information

COSC 2007 Data Structures II Final Exam. Part 1: multiple choice (1 mark each, total 30 marks, circle the correct answer)

COSC 2007 Data Structures II Final Exam. Part 1: multiple choice (1 mark each, total 30 marks, circle the correct answer) COSC 2007 Data Structures II Final Exam Thursday, April 13 th, 2006 This is a closed book and closed notes exam. There are total 3 parts. Please answer the questions in the provided space and use back

More information

Trees, Binary Trees, and Binary Search Trees

Trees, Binary Trees, and Binary Search Trees COMP171 Trees, Binary Trees, and Binary Search Trees 2 Trees Linear access time of linked lists is prohibitive Does there exist any simple data structure for which the running time of most operations (search,

More information

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours TED (10)-3071 Reg. No.. (REVISION-2010) (Maximum marks: 100) Signature. FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours PART

More information

Data Structure Lecture#10: Binary Trees (Chapter 5) U Kang Seoul National University

Data Structure Lecture#10: Binary Trees (Chapter 5) U Kang Seoul National University Data Structure Lecture#10: Binary Trees (Chapter 5) U Kang Seoul National University U Kang (2016) 1 In This Lecture The concept of binary tree, its terms, and its operations Full binary tree theorem Idea

More information

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 The data of the problem is of 2GB and the hard disk is of 1GB capacity, to solve this problem we should Use better data structures

More information

Associate Professor Dr. Raed Ibraheem Hamed

Associate Professor Dr. Raed Ibraheem Hamed Associate Professor Dr. Raed Ibraheem Hamed University of Human Development, College of Science and Technology Computer Science Department 2015 2016 Department of Computer Science _ UHD 1 What this Lecture

More information

Threaded Binary Trees

Threaded Binary Trees ES 0: Data Structures and Algorithms 202 Threaded Binary Trees Atul Gupta Binary Tree Traversals Depth-First Traversals Pre-order Post-order In-order Breadth First Traversals Note that. these traversals

More information

E.G.S. PILLAY ENGINEERING COLLEGE (An Autonomous Institution, Affiliated to Anna University, Chennai) Nagore Post, Nagapattinam , Tamilnadu.

E.G.S. PILLAY ENGINEERING COLLEGE (An Autonomous Institution, Affiliated to Anna University, Chennai) Nagore Post, Nagapattinam , Tamilnadu. 17CA 104DATA STRUCTURES Academic Year : 018-019 Programme : MCA Year / Semester : I / I Question Bank Course Coordinator: Mrs. C.Mallika Course Objectives The student should be able to 1. To understand

More information

Lecture 32. No computer use today. Reminders: Homework 11 is due today. Project 6 is due next Friday. Questions?

Lecture 32. No computer use today. Reminders: Homework 11 is due today. Project 6 is due next Friday. Questions? Lecture 32 No computer use today. Reminders: Homework 11 is due today. Project 6 is due next Friday. Questions? Friday, April 1 CS 215 Fundamentals of Programming II - Lecture 32 1 Outline Introduction

More information

Section Summary. Introduction to Trees Rooted Trees Trees as Models Properties of Trees

Section Summary. Introduction to Trees Rooted Trees Trees as Models Properties of Trees Chapter 11 Copyright McGraw-Hill Education. All rights reserved. No reproduction or distribution without the prior written consent of McGraw-Hill Education. Chapter Summary Introduction to Trees Applications

More information

Tree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example.

Tree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example. Trees, Binary Search Trees, and Heaps CS 5301 Fall 2013 Jill Seaman Tree: non-recursive definition Tree: set of nodes and directed edges - root: one node is distinguished as the root - Every node (except

More information

Uses for Trees About Trees Binary Trees. Trees. Seth Long. January 31, 2010

Uses for Trees About Trees Binary Trees. Trees. Seth Long. January 31, 2010 Uses for About Binary January 31, 2010 Uses for About Binary Uses for Uses for About Basic Idea Implementing Binary Example: Expression Binary Search Uses for Uses for About Binary Uses for Storage Binary

More information

Outline. Preliminaries. Binary Trees Binary Search Trees. What is Tree? Implementation of Trees using C++ Tree traversals and applications

Outline. Preliminaries. Binary Trees Binary Search Trees. What is Tree? Implementation of Trees using C++ Tree traversals and applications Trees 1 Outline Preliminaries What is Tree? Implementation of Trees using C++ Tree traversals and applications Binary Trees Binary Search Trees Structure and operations Analysis 2 What is a Tree? A tree

More information

Chapter 5. Binary Trees

Chapter 5. Binary Trees Chapter 5 Binary Trees Definitions and Properties A binary tree is made up of a finite set of elements called nodes It consists of a root and two subtrees There is an edge from the root to its children

More information

COMP : Trees. COMP20012 Trees 219

COMP : Trees. COMP20012 Trees 219 COMP20012 3: Trees COMP20012 Trees 219 Trees Seen lots of examples. Parse Trees Decision Trees Search Trees Family Trees Hierarchical Structures Management Directories COMP20012 Trees 220 Trees have natural

More information

Data Structures and Algorithms (DSA) Course 9 Lists / Graphs / Trees. Iulian Năstac

Data Structures and Algorithms (DSA) Course 9 Lists / Graphs / Trees. Iulian Năstac Data Structures and Algorithms (DSA) Course 9 Lists / Graphs / Trees Iulian Năstac Recapitulation It is considered the following type: typedef struct nod { ; struct nod *next; } NOD; 2 Circular

More information

Fundamentals of Data Structure

Fundamentals of Data Structure Fundamentals of Data Structure Set-1 1. Which if the following is/are the levels of implementation of data structure A) Abstract level B) Application level C) Implementation level D) All of the above 2.

More information

ROOT: A node which doesn't have a parent. In the above tree. The Root is A.

ROOT: A node which doesn't have a parent. In the above tree. The Root is A. TREE: A tree is a finite set of one or more nodes such that there is a specially designated node called the Root, and zero or more non empty sub trees T 1, T 2...T k, each of whose roots are connected

More information

tree nonlinear Examples

tree nonlinear Examples The Tree ADT Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary tree implementation Examine a binary tree example 10-2

More information

Binary Trees. College of Computing & Information Technology King Abdulaziz University. CPCS-204 Data Structures I

Binary Trees. College of Computing & Information Technology King Abdulaziz University. CPCS-204 Data Structures I Binary Trees College of Computing & Information Technology King Abdulaziz University CPCS-204 Data Structures I Outline Tree Stuff Trees Binary Trees Implementation of a Binary Tree Tree Traversals Depth

More information

MIDTERM EXAMINATION Spring 2010 CS301- Data Structures

MIDTERM EXAMINATION Spring 2010 CS301- Data Structures MIDTERM EXAMINATION Spring 2010 CS301- Data Structures Question No: 1 Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the

More information

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified) WINTER 18 EXAMINATION Subject Name: Data Structure Model wer Subject Code: 17330 Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in

More information

Objective Questions for Online Practical Exams under CBCS Scheme Subject: Data Structure-I (CS-113)

Objective Questions for Online Practical Exams under CBCS Scheme Subject: Data Structure-I (CS-113) Objective Questions for Online Practical Exams under CBCS Scheme Subject: Data Structure-I (CS-113) 1. The number of interchanges required to sort 5, 1, 6, 2 4 in ascending order using Bubble Sort (A)

More information

UNIT III TREES. A tree is a non-linear data structure that is used to represents hierarchical relationships between individual data items.

UNIT III TREES. A tree is a non-linear data structure that is used to represents hierarchical relationships between individual data items. UNIT III TREES A tree is a non-linear data structure that is used to represents hierarchical relationships between individual data items. Tree: A tree is a finite set of one or more nodes such that, there

More information