# Data Structure with C

Save this PDF as:

Size: px
Start display at page:

## Transcription

1 Subject: Data Structure with C Topic : Tree Tree A tree is a set of nodes that either:is empty or has a designated node, called the root, from which hierarchically descend zero or more subtrees, which are also trees. Fundamentals of TREES Tree is a Data structure that matches the shape of tree root: node with no parent, A non-empty tree has exactly one root leaf: node with no children Siblings/Brothers/Sisters: two nodes with the same parent. path: a sequence of nodes n1, n2,, nk such that ni is the parent of ni+1 for 1 i < k in other words, a sequence of hops to get from one node to another the length of a path is the number of edges in the path, or 1 less than the number of nodes in it M-ary: A tree with each node can maximum of M nodes, for Binary tree where M=2, all these terminology explained in figure 1 and figure 2. Figure 1: Tree example

2 Figure 2: Tree example TREES Representation General Tree organization chart format, Indented list bill-of-materials system in which a parts list represents the assembly structure of an item as shown in the figure 3. Computer Parts as a General TREE Figure 3: General tree example

3 BINARY TREES A binary tree is a finite set of elements that is either empty or is partitioned into two disjoint subsets. The first subset contains a single element called the root of the tree. The other two subsets are themselves binary trees, called the left and right subtrees of the original tree. A left or right subtree can be empty. Each element of a binary tree is called a node of the tree as illustrated in figure 4. Figure 4: Tree example If A is the root of a binary tree and B is the root of its left or right subtree, then A is said to be the father of B and B is said to be the left or right son of A and collection of binary shown in figure 5.

4 Figure 5: Versions of binary tree A node that has no sons is called a leaf. Node n1 is an ancestor of node n2 (and n2 is a descendant of n 1) if n1 is either the father of n2 or the father of some ancestor of n2. node n2 is a left descendant of node n1 if n2 is either the left son of n1 or a descendant of the left son of n1. A right descendant may be similarly defined. Two nodes are brothers if they are left and right sons of the same father. Minimum number of nodes BINARY TREES Given a height of the binary tree, H, the minimum number of nodes in the tree is given as shown in the figure 6.

5 . Figure 6: Minimum node binary tree Maximum number of nodes BT Maximum number of nodes is derived from the fact that each node can have only two descendents. Given a height of the binary tree, H, the maximum number of nodes in the tree is as shown in the figure 7 Figure 7:Maximum nodes of binary tree Strictly BINARY TREES If every nonleaf node in a binary tree has nonempty left and right subtrees, the tree is termed a strictly binary tree. A strictly binary tree with n leaves always contains 2n-1 nodes as illustrated in figure 8.

6 Figure 8: strictly binary tree Not Strictly BINARY TREES A strictly binary tree with n leaves always contains 2n-1 nodes. Figure 9: Not strictly binary tree Level of BINARY TREES The level of a node in a binary tree is defined as follows. The root has level 0, and the level of any other node in the tree is one more than the level of its father.

7 Figure 10: Levels of binary tree Depth of BINARY TREES The depth or Hieght of a binary tree is the maximum level of any leaf in the tree. By definition the height of any empty tree is -1. This equals the length of the longest path from the root to any leaf. Complete BINARY TREES A complete binary tree of depth d is the strictly binary tree all of whose leaves are at level d. If a binary tree contains m nodes at level l, it contains at most 2m nodes at level l+1. A complete binary tree of depth d is the strictly binary tree all of whose leaves are at level d. Since a binary tree can contain at most one node at level 0 (the root), it can contain at most 2 / nodes at level l and typical tree having defth is as shown in the figure 11. Figure 11:tree of depth 3.

8 A complete binary tree of depth d that contains exactly 2 l nodes at each level l between 0 and d. (This is equivalent to saying that it is the binary tree of depth d that contains exactly 2d nodes at level d.) The total number of nodes in a complete binary tree of depth d, tn equals the sum of the number of nodes at each level between 0 and d. tn = d = j=0,d 2 j A binary tree of depth d is an almost complete binary tree if: 1. Any node nd at level less than d-1 has two sons. 2. For any node nd in the tree with a right descendant at level d, nd must have a left son and every left descendant of nd is either a leaf at level d or has two sons. Figure 12: Examples of strictly binary tree Almost Complete BT The strictly binary tree of (a) is not almost complete, since it contains leaves at levels 1, 2 and 3, thereby violating condition 1, as narrated in figure 12(a).

9 The strictly binary tree of 12(b) satisfies condition 1, since every leaf is either at level 2 or at level 3. However, condition 2 is violated, since A has a right descendant at level 3 (J) but also has a left descendant that is a leaf at level 2 (E) as illustrated in figure 12(b). The strictly binary tree of figure 12(c) satisfies both conditions 1 and 2. The binary tree of figure 12(d) is also an almost complete binary tree but it is not strictly binary, since node E has a left son but not a right son. The nodes of an almost complete binary tree can be numbered so that the root is assigned the number 1, a left son is assigned twice the number assigned its father, and a right son is assigned one more than twice the number assigned its father. An almost complete strictly binary tree with n leaves has 2n -1 nodes, as does any other strictly binary tree with n leaves. An almost complete binary tree with n leaves that is not strictly binary has 2n nodes. OPERATIONS ON BINARY TREES(BT) There are a number of primitive operations that can be applied to a binary tree. If p is a pointer to a node nd of a binary tree, the function info(p) returns the contents of nd. The functions returns the pointers to the left(p)- left son of nd right(p)- right son of nd father(p)- father of nd brother(p) - brother of nd These functions return the null pointer if nd has no left son, right son, father, or brother. Finally, the logical functions isleft(p) and isright(p) return the value true if nd is a left or right son respectively, of some other node in the tree, and false otherwise.in constructing a binary tree, the following operations are useful. maketree(x) creates a new binary tree consisting of a single node with information field x and returns a pointer to that node. setleft(p,x) accepts a pointer p to a binary tree node with no left son. In constructing a binary tree, It creates a new left son of node(p) with information field x. setright(p,x) is analogous to setleft except that it creates a right son of node(p). APPLICATIONS Suppose we want to find all duplicates in a list of numbers. One way of doing this is to compare each number with all those that precede it. However, this involves a large number of comparisons. The number of comparisons can be reduced by using a binary tree.

10 Find all duplicates in List The first number in the list is placed in a node that is established as the root of a binary tree with empty left and right subtrees. Each successive number in the list is then compared to the number in the root. If it matches, we have a duplicate. If it is smaller, we examine the left subtree; if it is larger, we examine the right subtree. If the subtree is empty, the number is not a duplicate and is placed into a new node at that position in the tree. If the subtree is nonempty, we compare the number to the contents of the root of the subtree and the entire process is repeated with the subtree. /* read the 1st number and insert it into a single-node binary tree*/ scanf("%d", &number); tree = maketree(number)] while (there are numbers left in the input) { scanf("%d", &number); p = q = tree; while (number!= info(p) && q!= NULL} { p = q; if (number < info(p)) q = left(p); else q = right(p); } I* end while */ if (number==info(p)) printf("%d %s\n", number, "is a duplicate"); /* insert number to the right or left of p */ else if (number < info(p)) setleft(p, number); else setright(p, number); }/* end while */ Another common operation is to traverse a binary tree; that is, to pass through the tree, enumerating each of its nodes once.we may simply wish to print the contents of each node as we enumerate it, or we may wish to process it in some other fashion. Traverse of BT The order in which the nodes of a linear list are visited in a traversal is clearly from first to last. However, there is no such "natural" linear order for the nodes of a tree. Thus, different orderings are used for traversal in different cases. Let L, V, and R stand for moving left, visiting the node, and moving right. There are six possible combinations of traversal. LVR, LRV, VLR, VRL, RVL, RLV. Adopt

11 convention that we traverse left before right, only 3 traversals remain LVR, LRV, VLR and in fact they are inorder, postorder and preorder approaches are explained in figure 13. Tree Traversal Approaches Figure 13: Examples of tree traversal ***************** *********** Pre-order on BINARY TREES To traverse a nonempty binary tree in preorder (also known as depth-first order), detail procedure is illustrated in figure 14 and figure 15. We perform the following three operations: 1. Visit the root. 2. Traverse the left subtree in preorder. 3. Traverse the right subtree in preorder.

12 Figure 14: Pre order tree traversal Figure 15: Pre order tree traversal

13 Example of Pre-Order order: C F T B R K G, The trick: Walk around the outside of the tree and emit a node's value when you touch the left side of the node and it is narrated in figure 16. Figure 16: Pre order tree traversal In-order on BINARY TREES To traverse a nonempty binary tree in inorder (or symmetric order), it is explained in figure Traverse the left subtree in inorder. 2. Visit the root. 3. Traverse the right subtree in inorder. Figure 17: In order tree traversal

14 Example of In-order order: B T R F K C G, The trick: Walk around the outside of the tree and emit a node's value when you touch the bottom side of the node and it is explained in figure 18. Figure 18: In order tree traversal Post-Order on BINARY TREES To traverse a nonempty binary tree in postorder and it is explained in figure Traverse the left subtree in postorder. 2. Traverse the right subtree in postorder. 3. Visit the root. Figure 19: Post order tree traversal

15 Example of Post-Order order: B R T K F G C, The trick: Walk around the outside of the tree and emit a node's value when you touch the right side of the node and it is portrayed in figure 20. The tree methods further demonstrated in figure 21. Figure 20: Post order tree traversal Figure 21: Examples of tree traversal ************ *********************

16 APPLICATIONS OF BINARY TREES An example of sorting method illustrate in the following paragraph. As we read the numbers, they can be inserted into a binary tree. However, unlike the algorithm used to find duplicates, duplicate values are also placed in the tree. When a number is compared with the contents of a node in the tree, a left branch is taken if the number is smaller than the contents of the node and a right branch if it is greater or equal to the contents of the node. If the input list is as follows and corresponding shown in figure Figure 22 : BT Such a binary tree has the property that all elements in the left subtree of a node n are less than the contents of n, and all elements in the right subtree of n are greater than or equal to the contents of n. A binary tree that has this property is called a binary search tree. Another application of binary trees: representing an expression containing operands and binary operators by a strictly binary tree. The root of the strictly binary tree contains an operator that is to be applied to the results of evaluating the expressions represented by the left and right subtrees. A node representing an operator is a nonleaf, whereas a node representing an operand is a leaf. Traversing a tree in preorder means that the operator (the root) precedes its two operands (the subtrees). Thus a preorder traversal yields the prefix form of the expression. Traversing a binary expression tree in postorder places an operator after its two operands, so that a postorder traversal produces the postfix form of the expression, pre order and post order concpte employed in figure 23.

17 Preorder: +A*BC Postorder: ABC* + Preorder: *+ABC Postorder: AB + C* Figure 23: Examples of tree traversal Node Representation of Binary Trees As is the case with list nodes, tree nodes may be implemented as array elements or as allocations of a dynamic variable. Each node contains info, left, right, and father fields. The left, right, and father fields of a node point to the node's left son, right son, and father, respectively. #define NUMNODES 500 struct nodetype { int info; int left; int right; int father; }; struct nodetype node [NUMNODES]; Under this representation, the operations info(p), left(p), right(p), and father(p) are implemented by references to node[p].info, node[p].left, node[p].right, and node[p].father, respectively. The root is uniquely identified by a NULL value (-1) in its father field. The external pointer to a tree usually points to its root. Once the array of nodes is declared, we could create an available list by executing the following statements: int avail, i; { avail = 1; for (i=0; i < NUMNODES; i++) node [i]. left = i + 1; node [NUMNODES-1]. left = 0;

18 } The available list is not a binary tree but a linear list whose nodes are linked together by the left field. Each node in a tree is taken from the available pool when needed and returned to the available pool when no longer in use. This representation is called the linked array representation of a binary tree. Alternatively, a node may be defined by struct nodetype { int info; struct nodetype *left; struct nodetype *right; struct nodetype *father; }; typedef struct nodetype *NODEPTR; The operations info(p), left(p), right(p), and father(p) would be implemented by references to p->info, p->left, p->right, and p->father, respectively. The routines getnode and freenode simply allocate and free nodes using the routines malloc and free. maketree function This representation is called the dynamic node representation of a binary tree. The maketree function, which allocates a node and sets it as the root of a single-node binary tree, may be written as follows: under the dynamic node representation NODEPTR maketree(int x) { NODEPTR p; p = getnode(); p->info = x; p->left = NULL; p->right = NULL; return(p); } /* end maketree */ setleft( p,x) The routine setleft( p,x) sets a node with contents x as the left son of node( p): void setleft(nodeptr p, int x) { if (p == NULL) printf("void insertion\n"); else if (p->left!=null) printf ("invalid insertion\n"); else p->left = maketree(x); } /* end setleft */

19 Internal and External Nodes of BT By definition leaf nodes have no sons. Thus, in the linked representation of binary trees, left and right pointers are needed only in nonleaf nodes. Sometimes two separate sets of nodes are used for non-leaves and leaves. Nonleaf nodes contain info, left, and right fields and are allocated as dynamic records or as an array of records managed using an available list. Leaf nodes do not contain a left or right field and are kept as a single info array that is allocated sequentially as needed When this distinction is made between nonleaf and leaf nodes, nonleaves are called internal nodes and leaves are called external nodes. Of course, a son pointer within an internal node must be identified as pointing to an internal or an external node. This can be done in two ways. One technique is to declare two different node types and pointer types and to use a union for internal nodes, with each alternative containing one of the two pointer types. The other technique is to retain a single type of pointer and a single type of node, where the node is a union that does (if the node is an internal node) or does not (if an external node) contain left and right pointer fields. The n nodes of an almost complete binary tree can be numbered from 1 to n, so that the number assigned a left son is twice the number assigned its father, and the number assigned a right son is 1 more than twice the number assigned its father. We can represent an almost complete binary tree without father, left, or right links. Implicit Array Representation BT The n nodes of an almost complete binary tree can be numbered from 1 to n, so that the number assigned a left son is twice the number assigned its father, and the number assigned a right son is 1 more than twice the number assigned its father. We can represent an almost complete binary tree without father, left, or right links. Instead, the nodes can be kept in an array info of size n. In C, arrays start at position 0; therefore instead of numbering the tree nodes from 1 to n, we number them from 0 to n - 1. Because of the one-position shift, the two sons of a node numbered p are in positions 2p + 1 and 2p + 2, instead of 2p and 2p + 1.The root of the tree is at position 0, so that tree, the external pointer to the tree root, always equals 0. The node in position p is the implicit father of nodes 2p + 1 and 2p + 2. The left son of node p is node 2p + 1 and its right son is node 2p + 2 and it is elaborated in figure 24.

20 Figure 24: Examples of tree traversal This implicit array representation of almost complete binary trees can be extended to an implicit array representation of binary trees generally. The implicit array representation is also called the sequential representation. Because it allows a tree to be implemented in a contiguous block of memory rather than via pointers connecting widely separated nodes.under the sequential representation, an array element is allocated whether or not it serves to contain a node of a tree. We must, therefore, flag unused array elements as nonexistent, or null, tree nodes. This may be accomplished by one of two methods. One method is to set info[p] to a special value if node p is null. Alternatively, we may add a logical flag field, used, to each node. Each node then contains two fields: info and used. The entire structure is contained in an array node. used(p) implemented as node[p].used, is TRUE if node p is not a null node and FALSE if it is a null node. Choosing a BT Representation Which representation of binary trees is preferable? The sequential representation is somewhat simpler, although it is necessary to ensure that all pointers are within the array bounds. It clearly saves storage space for trees known to be almost complete, since it eliminates the need for the fields left, right, and father and does not even require a used field. It is also space efficient for trees that are only a few nodes short of being almost complete, or when nodes are successively eliminated from a tree that originates as almost complete, although a used field might then be required. This representation can only be used in a context in which only a single tree is required, or where the number of trees needed and each of their maximum sizes is fixed in

21 advance. We may implement the traversal of binary trees in C by recursive routines that mirror the traversal definitions. These are pretrav, intrav, and posttrav print the contents of a binary tree in preorder, inorder, and postorder, respectively. The parameter to each routine is a pointer to the root node of a binary tree. Binary Tree Traversals in C Pre Order Traversals in C void pretrav(nodeptr tree) { if (tree!= NULL) { printf("%d\n", tree->info); pretrav(tree->1eft); pretrav(tree->right); } /* end if */ } /* end pretrav */ In Order Traversals in C void intrav(nodeptr tree) { if (tree!= NULL) { jntrav(tree->left); printf("%d\n", tree->info); intrav(tree->right); } /* end if */ } I* end intrav */ Post Order Traversals in C void posttrav(nodeptr tree) { if (tree!= NULL) { posttrav(tree->left); posttrav(tree->right); printf("%d\n", tree->info); } /* end if */ } /* end posttrav */

22 Binary Tree Traversals in C These routines could be written nonrecursively to perform the necessary stacking and unstacking explicitly. For example the following is a nonrecursive routine to traverse a binary tree in inorder: Non recursive Inorder #define MAXSTACK 100 void intrav2(nodeptr tree) { struct stack { int top; NODEPTR item[maxstack]; } s; NODEPTR p; s.top = -1; p = tree; do {/* travel down left branches as far as possible */ /* saving pointers to nodes passed */ while (p!= NULL) { push (s, p); p = p->left; } /* end while */ /* check if finished */ if (!empty(s)) {/* at this point the left subtree is empty */ p = pop(s); printf("%d\n", p->info); /* visit the root */ p = p->right; /* traverse right subtree */ } /* end if */ } while (!empty(s) II p!= NULL); } /* end intrav2 */a Comparison of Recursive with Iterative If both routines are executed, the recursive intrav generally executes much more quickly than the nonrecursive intrav2. This goes against the accepted "folk wisdom" that recursion is slower than iteration. The primary cause ofthe inefficiency of iterative - intrav2 as written is the calls to push, pop, and empty. Even when the code for these functions is inserted in-line into intrav2, it is still slower than intrav because of the often superfluous tests for overflow and underflow included in that code. Yet, even when the underflow/overflow tests are removed, intrav is faster than intrav2 under a compiler that implements recursion efficiently! The efficiency of the recursive process in this case is due to a number of factors: 1. There is no "extra" recursion, as there is in computing the Fibonacci numbers, where f(n-2) and f(n-1) are both recomputed separately even though the value of f(n - 2) is used in computing f(n - 1).

23 2. The recursion stack cannot be entirely eliminated, as it can be in computing the factorial function. Thus, the automatic stacking and unstacking of built-in recursion is more efficient than the programmed version. 3. There are no extraneous parameters and local variables, as there are, For example in some versions of binary search, the automatic stacking of recursion does not stack any more variables than are necessary. Heterogeneous Binary Trees Often the information contained in different nodes of a binary tree is not all of the same type. For example in representing a binary expression with constant numerical operands we may wish to use a binary tree whose leaves contain numbers but whose nonleaf nodes contain characters representing operators. To represent such a tree in C we may use a union to represent the information portion of the node. Of course, each tree node must contain within itself a field to indicate the type of object that its info field contains. #define OPERATOR 0 #define OPERAND 1 struct nodetype { short int utype; /* OPERATOR or OPERAND */ union { char chinfo; float numinfo; } info; struct nodetype *left; struct nodetype *right; }; typedef struct nodetype *NODEPTR; Figure 25: Examples of tree traversal Binary tree representing the expression as follows: * (6-7)/5 + 3.

### 1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Answer the following 1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ 2) Which data structure is needed to convert infix notations to postfix notations? Stack 3) The

### 10CS35: Data Structures Using C

CS35: Data Structures Using C QUESTION BANK REVIEW OF STRUCTURES AND POINTERS, INTRODUCTION TO SPECIAL FEATURES OF C OBJECTIVE: Learn : Usage of structures, unions - a conventional tool for handling a

### TREE BASIC TERMINOLOGIES

TREE Trees are very flexible, versatile and powerful non-liner data structure that can be used to represent data items possessing hierarchical relationship between the grand father and his children and

### The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).

CHAPTER 5 The Tree Data Model There are many situations in which information has a hierarchical or nested structure like that found in family trees or organization charts. The abstraction that models hierarchical

### Output: 12 18 30 72 90 87. struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

50 20 70 10 30 69 90 14 35 68 85 98 16 22 60 34 (c) Execute the algorithm shown below using the tree shown above. Show the exact output produced by the algorithm. Assume that the initial call is: prob3(root)

### DATA STRUCTURES USING C

DATA STRUCTURES USING C QUESTION BANK UNIT I 1. Define data. 2. Define Entity. 3. Define information. 4. Define Array. 5. Define data structure. 6. Give any two applications of data structures. 7. Give

### 12 Abstract Data Types

12 Abstract Data Types 12.1 Source: 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).

### Binary Search Trees. A Generic Tree. Binary Trees. Nodes in a binary search tree ( B-S-T) are of the form. P parent. Key. Satellite data L R

Binary Search Trees A Generic Tree Nodes in a binary search tree ( B-S-T) are of the form P parent Key A Satellite data L R B C D E F G H I J The B-S-T has a root node which is the only node whose parent

### PES Institute of Technology-BSC QUESTION BANK

PES Institute of Technology-BSC Faculty: Mrs. R.Bharathi CS35: Data Structures Using C QUESTION BANK UNIT I -BASIC CONCEPTS 1. What is an ADT? Briefly explain the categories that classify the functions

### Previous Lectures. B-Trees. External storage. Two types of memory. B-trees. Main principles

B-Trees Algorithms and data structures for external memory as opposed to the main memory B-Trees Previous Lectures Height balanced binary search trees: AVL trees, red-black trees. Multiway search trees:

### Ordered Lists and Binary Trees

Data Structures and Algorithms Ordered Lists and Binary Trees Chris Brooks Department of Computer Science University of San Francisco Department of Computer Science University of San Francisco p.1/62 6-0:

### Binary Trees and Huffman Encoding Binary Search Trees

Binary Trees and Huffman Encoding Binary Search Trees Computer Science E119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Motivation: Maintaining a Sorted Collection of Data A data dictionary

### Binary Search Trees (BST)

Binary Search Trees (BST) 1. Hierarchical data structure with a single reference to node 2. Each node has at most two child nodes (a left and a right child) 3. Nodes are organized by the Binary Search

### root node level: internal node edge leaf node CS@VT Data Structures & Algorithms 2000-2009 McQuain

inary Trees 1 A binary tree is either empty, or it consists of a node called the root together with two binary trees called the left subtree and the right subtree of the root, which are disjoint from each

### UNIVERSITI MALAYSIA SARAWAK KOTA SAMARAHAN SARAWAK PSD2023 ALGORITHM & DATA STRUCTURE

STUDENT IDENTIFICATION NO UNIVERSITI MALAYSIA SARAWAK 94300 KOTA SAMARAHAN SARAWAK FAKULTI SAINS KOMPUTER & TEKNOLOGI MAKLUMAT (Faculty of Computer Science & Information Technology) Diploma in Multimedia

### Parallelization: Binary Tree Traversal

By Aaron Weeden and Patrick Royal Shodor Education Foundation, Inc. August 2012 Introduction: According to Moore s law, the number of transistors on a computer chip doubles roughly every two years. First

### B-Trees. Algorithms and data structures for external memory as opposed to the main memory B-Trees. B -trees

B-Trees Algorithms and data structures for external memory as opposed to the main memory B-Trees Previous Lectures Height balanced binary search trees: AVL trees, red-black trees. Multiway search trees:

### Converting a Number from Decimal to Binary

Converting a Number from Decimal to Binary Convert nonnegative integer in decimal format (base 10) into equivalent binary number (base 2) Rightmost bit of x Remainder of x after division by two Recursive

### Home Page. Data Structures. Title Page. Page 1 of 24. Go Back. Full Screen. Close. Quit

Data Structures Page 1 of 24 A.1. Arrays (Vectors) n-element vector start address + ielementsize 0 +1 +2 +3 +4... +n-1 start address continuous memory block static, if size is known at compile time dynamic,

### Data Structures. Level 6 C30151. www.fetac.ie. Module Descriptor

The Further Education and Training Awards Council (FETAC) was set up as a statutory body on 11 June 2001 by the Minister for Education and Science. Under the Qualifications (Education & Training) Act,

### Data Structures and Algorithms

Data Structures and Algorithms CS245-2016S-06 Binary Search Trees David Galles Department of Computer Science University of San Francisco 06-0: Ordered List ADT Operations: Insert an element in the list

### Analysis of Algorithms I: Binary Search Trees

Analysis of Algorithms I: Binary Search Trees Xi Chen Columbia University Hash table: A data structure that maintains a subset of keys from a universe set U = {0, 1,..., p 1} and supports all three dictionary

### Stacks. Linear data structures

Stacks Linear data structures Collection of components that can be arranged as a straight line Data structure grows or shrinks as we add or remove objects ADTs provide an abstract layer for various operations

### Data Structure [Question Bank]

Unit I (Analysis of Algorithms) 1. What are algorithms and how they are useful? 2. Describe the factor on best algorithms depends on? 3. Differentiate: Correct & Incorrect Algorithms? 4. Write short note:

### Binary Search Trees CMPSC 122

Binary Search Trees CMPSC 122 Note: This notes packet has significant overlap with the first set of trees notes I do in CMPSC 360, but goes into much greater depth on turning BSTs into pseudocode than

### AS-2261 M.Sc.(First Semester) Examination-2013 Paper -fourth Subject-Data structure with algorithm

AS-2261 M.Sc.(First Semester) Examination-2013 Paper -fourth Subject-Data structure with algorithm Time: Three Hours] [Maximum Marks: 60 Note Attempts all the questions. All carry equal marks Section A

### Algorithms and Data Structures

Algorithms and Data Structures Part 2: Data Structures PD Dr. rer. nat. habil. Ralf-Peter Mundani Computation in Engineering (CiE) Summer Term 2016 Overview general linked lists stacks queues trees 2 2

### Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the

### Data Structures and Algorithms(5)

Ming Zhang Data Structures and Algorithms Data Structures and Algorithms(5) Instructor: Ming Zhang Textbook Authors: Ming Zhang, Tengjiao Wang and Haiyan Zhao Higher Education Press, 2008.6 (the "Eleventh

### Learning Outcomes. COMP202 Complexity of Algorithms. Binary Search Trees and Other Search Trees

Learning Outcomes COMP202 Complexity of Algorithms Binary Search Trees and Other Search Trees [See relevant sections in chapters 2 and 3 in Goodrich and Tamassia.] At the conclusion of this set of lecture

### INTERNATIONAL JOURNAL OF PURE AND APPLIED RESEARCH IN ENGINEERING AND TECHNOLOGY

INTERNATIONAL JOURNAL OF PURE AND APPLIED RESEARCH IN ENGINEERING AND TECHNOLOGY A PATH FOR HORIZING YOUR INNOVATIVE WORK A REVIEW ON THE USAGE OF OLD AND NEW DATA STRUCTURE ARRAYS, LINKED LIST, STACK,

### Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

Questions 1 through 25 are worth 2 points each. Choose one best answer for each. 1. For the singly linked list implementation of the queue, where are the enqueues and dequeues performed? c a. Enqueue in

### 1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D. base address 2. The memory address of fifth element of an array can be calculated

### Algorithms Chapter 12 Binary Search Trees

Algorithms Chapter 1 Binary Search Trees Outline Assistant Professor: Ching Chi Lin 林 清 池 助 理 教 授 chingchi.lin@gmail.com Department of Computer Science and Engineering National Taiwan Ocean University

### 5. A full binary tree with n leaves contains [A] n nodes. [B] log n 2 nodes. [C] 2n 1 nodes. [D] n 2 nodes.

1. The advantage of.. is that they solve the problem if sequential storage representation. But disadvantage in that is they are sequential lists. [A] Lists [B] Linked Lists [A] Trees [A] Queues 2. The

### Common Data Structures

Data Structures 1 Common Data Structures Arrays (single and multiple dimensional) Linked Lists Stacks Queues Trees Graphs You should already be familiar with arrays, so they will not be discussed. Trees

### Binary Heap Algorithms

CS Data Structures and Algorithms Lecture Slides Wednesday, April 5, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks CHAPPELLG@member.ams.org 2005 2009 Glenn G. Chappell

### Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010 Problem 1. In each of the following question, please specify if the statement

### GUJARAT TECHNOLOGICAL UNIVERSITY, AHMEDABAD, GUJARAT. Course Curriculum. DATA STRUCTURES (Code: 3330704)

GUJARAT TECHNOLOGICAL UNIVERSITY, AHMEDABAD, GUJARAT Course Curriculum DATA STRUCTURES (Code: 3330704) Diploma Programme in which this course is offered Semester in which offered Computer Engineering,

### MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push) -----------------------------------------

=============================================================================================================================== DATA STRUCTURE PSEUDO-CODE EXAMPLES (c) Mubashir N. Mir - www.mubashirnabi.com

### A binary search tree is a binary tree with a special property called the BST-property, which is given as follows:

Chapter 12: Binary Search Trees A binary search tree is a binary tree with a special property called the BST-property, which is given as follows: For all nodes x and y, if y belongs to the left subtree

### ER E P M A S S I CONSTRUCTING A BINARY TREE EFFICIENTLYFROM ITS TRAVERSALS DEPARTMENT OF COMPUTER SCIENCE UNIVERSITY OF TAMPERE REPORT A-1998-5

S I N S UN I ER E P S I T VER M A TA S CONSTRUCTING A BINARY TREE EFFICIENTLYFROM ITS TRAVERSALS DEPARTMENT OF COMPUTER SCIENCE UNIVERSITY OF TAMPERE REPORT A-1998-5 UNIVERSITY OF TAMPERE DEPARTMENT OF

### Data Structures Using C++

Data Structures Using C++ 1.1 Introduction Data structure is an implementation of an abstract data type having its own set of data elements along with functions to perform operations on that data. Arrays

### Exercises Software Development I. 11 Recursion, Binary (Search) Trees. Towers of Hanoi // Tree Traversal. January 16, 2013

Exercises Software Development I 11 Recursion, Binary (Search) Trees Towers of Hanoi // Tree Traversal January 16, 2013 Software Development I Winter term 2012/2013 Institute for Pervasive Computing Johannes

### A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Binary Search Trees 1 The general binary tree shown in the previous chapter is not terribly useful in practice. The chief use of binary trees is for providing rapid access to data (indexing, if you will)

### B+ Tree Properties B+ Tree Searching B+ Tree Insertion B+ Tree Deletion Static Hashing Extendable Hashing Questions in pass papers

B+ Tree and Hashing B+ Tree Properties B+ Tree Searching B+ Tree Insertion B+ Tree Deletion Static Hashing Extendable Hashing Questions in pass papers B+ Tree Properties Balanced Tree Same height for paths

### Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

### AP Computer Science AB Syllabus 1

AP Computer Science AB Syllabus 1 Course Resources Java Software Solutions for AP Computer Science, J. Lewis, W. Loftus, and C. Cocking, First Edition, 2004, Prentice Hall. Video: Sorting Out Sorting,

### UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything

### 1 2-3 Trees: The Basics

CS10: Data Structures and Object-Oriented Design (Fall 2013) November 1, 2013: 2-3 Trees: Inserting and Deleting Scribes: CS 10 Teaching Team Lecture Summary In this class, we investigated 2-3 Trees in

### Algorithms and Data Structures Written Exam Proposed SOLUTION

Algorithms and Data Structures Written Exam Proposed SOLUTION 2005-01-07 from 09:00 to 13:00 Allowed tools: A standard calculator. Grading criteria: You can get at most 30 points. For an E, 15 points are

### Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

Tutorial#1 Q 1:- Explain the terms data, elementary item, entity, primary key, domain, attribute and information? Also give examples in support of your answer? Q 2:- What is a Data Type? Differentiate

### Lecture Notes on Binary Search Trees

Lecture Notes on Binary Search Trees 15-122: Principles of Imperative Computation Frank Pfenning Lecture 17 March 17, 2010 1 Introduction In the previous two lectures we have seen how to exploit the structure

### Module 2 Stacks and Queues: Abstract Data Types

Module 2 Stacks and Queues: Abstract Data Types A stack is one of the most important and useful non-primitive linear data structure in computer science. It is an ordered collection of items into which

### Chapter 14 The Binary Search Tree

Chapter 14 The Binary Search Tree In Chapter 5 we discussed the binary search algorithm, which depends on a sorted vector. Although the binary search, being in O(lg(n)), is very efficient, inserting a

### Why Use Binary Trees?

Binary Search Trees Why Use Binary Trees? Searches are an important application. What other searches have we considered? brute force search (with array or linked list) O(N) binarysearch with a pre-sorted

### OPTIMAL BINARY SEARCH TREES

OPTIMAL BINARY SEARCH TREES 1. PREPARATION BEFORE LAB DATA STRUCTURES An optimal binary search tree is a binary search tree for which the nodes are arranged on levels such that the tree cost is minimum.

### ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION 2008-10-23/5:15-6:45 REC-200, EVI-350, RCH-106, HH-139

ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION 2008-10-23/5:15-6:45 REC-200, EVI-350, RCH-106, HH-139 Instructions: No aides. Turn off all electronic media and store them under your desk. If

### What Is Recursion? Recursion. Binary search example postponed to end of lecture

Recursion Binary search example postponed to end of lecture What Is Recursion? Recursive call A method call in which the method being called is the same as the one making the call Direct recursion Recursion

### 7.1 Our Current Model

Chapter 7 The Stack In this chapter we examine what is arguably the most important abstract data type in computer science, the stack. We will see that the stack ADT and its implementation are very simple.

### Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Quiz 4 Solutions Q1: What value does function mystery return when called with a value of 4? int mystery ( int number ) { if ( number

### Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive.

Recursion Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive. Why recursion? o For many problems, the recursion solution is more natural than the alternative

### BM267 - Introduction to Data Structures

BM267 - Introduction to Data Structures 3. Elementary Data Structures Ankara University Computer Engineering Department BLM267 1 Objectives Learn about elementary data structures - Data structures that

### Symbol Tables. Introduction

Symbol Tables Introduction A compiler needs to collect and use information about the names appearing in the source program. This information is entered into a data structure called a symbol table. The

### Chapter 8: Binary Trees

Chapter 8: Binary Trees Why Use Binary Trees? Tree Terminology An Analogy How Do Binary Search Trees Work Finding a Node Inserting a Node Traversing the Tree Finding Maximum and Minimum Values Deleting

### From Last Time: Remove (Delete) Operation

CSE 32 Lecture : More on Search Trees Today s Topics: Lazy Operations Run Time Analysis of Binary Search Tree Operations Balanced Search Trees AVL Trees and Rotations Covered in Chapter of the text From

### Binary Trees. Wellesley College CS230 Lecture 17 Thursday, April 5 Handout #28. PS4 due 1:30pm Tuesday, April 10 17-1

inary Trees Wellesley ollege S230 Lecture 17 Thursday, pril 5 Handout #28 PS4 due 1:30pm Tuesday, pril 10 17-1 Motivation: Inefficiency of Linear Structures Up to this point our focus has been linear structures:

### The Union-Find Problem Kruskal s algorithm for finding an MST presented us with a problem in data-structure design. As we looked at each edge,

The Union-Find Problem Kruskal s algorithm for finding an MST presented us with a problem in data-structure design. As we looked at each edge, cheapest first, we had to determine whether its two endpoints

### Binary Search Trees. Data in each node. Larger than the data in its left child Smaller than the data in its right child

Binary Search Trees Data in each node Larger than the data in its left child Smaller than the data in its right child FIGURE 11-6 Arbitrary binary tree FIGURE 11-7 Binary search tree Data Structures Using

### Any two nodes which are connected by an edge in a graph are called adjacent node.

. iscuss following. Graph graph G consist of a non empty set V called the set of nodes (points, vertices) of the graph, a set which is the set of edges and a mapping from the set of edges to a set of pairs

### CS711008Z Algorithm Design and Analysis

CS711008Z Algorithm Design and Analysis Lecture 7 Binary heap, binomial heap, and Fibonacci heap 1 Dongbo Bu Institute of Computing Technology Chinese Academy of Sciences, Beijing, China 1 The slides were

### 2. (a) Explain the strassen s matrix multiplication. (b) Write deletion algorithm, of Binary search tree. [8+8]

Code No: R05220502 Set No. 1 1. (a) Describe the performance analysis in detail. (b) Show that f 1 (n)+f 2 (n) = 0(max(g 1 (n), g 2 (n)) where f 1 (n) = 0(g 1 (n)) and f 2 (n) = 0(g 2 (n)). [8+8] 2. (a)

### CS 2412 Data Structures. Chapter 2 Stacks and recursion

CS 2412 Data Structures Chapter 2 Stacks and recursion 1 2.1 Stacks A stack is a data structure in which all insertions and deletions of entries are made at one end, called top of the stack. Examples:

### 1. Relational database accesses data in a sequential form. (Figures 7.1, 7.2)

Chapter 7 Data Structures for Computer Graphics (This chapter was written for programmers - option in lecture course) Any computer model of an Object must comprise three different types of entities: 1.

### The first step in solving a problem recursively is to formulate a recursive definition of the problem.

Chapter 8 Recursion The subject of this chapter is recursion, an implicit application of the stack ADT. A recursive method is a method that carries out its task by making a call(s) to itself. Each recursive

### Data Structures Using C++ 2E. Chapter 7 Stacks

Data Structures Using C++ 2E Chapter 7 Stacks Linked Implementation of Stacks Disadvantage of array (linear) stack representation Fixed number of elements can be pushed onto stack Solution Use pointer

### Heaps & Priority Queues in the C++ STL 2-3 Trees

Heaps & Priority Queues in the C++ STL 2-3 Trees CS 3 Data Structures and Algorithms Lecture Slides Friday, April 7, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks

### CSE 326: Data Structures B-Trees and B+ Trees

Announcements (4//08) CSE 26: Data Structures B-Trees and B+ Trees Brian Curless Spring 2008 Midterm on Friday Special office hour: 4:-5: Thursday in Jaech Gallery (6 th floor of CSE building) This is

### Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Definition Course: Programming II - Abstract Data Types The ADT Stack The ADT Stack is a linear sequence of an arbitrary number of items, together with access procedures. The access procedures permit insertions

### Data Structures UNIT III. Model Question Answer

Data Structures UNIT III Model Question Answer Q.1. Define Stack? What are the different primitive operations on Stack? Ans: Stack: A stack is a linear structure in which items may be added or removed

### CS 253: Algorithms. Chapter 12. Binary Search Trees. * Deletion and Problems. Credit: Dr. George Bebis

CS 2: Algorithms Chapter Binary Search Trees * Deletion and Problems Credit: Dr. George Bebis Binary Search Trees Tree representation: A linked data structure in which each node is an object Node representation:

### EE2204 DATA STRUCTURES AND ALGORITHM (Common to EEE, EIE & ICE)

EE2204 DATA STRUCTURES AND ALGORITHM (Common to EEE, EIE & ICE) UNIT I LINEAR STRUCTURES Abstract Data Types (ADT) List ADT array-based implementation linked list implementation cursor-based linked lists

### 2. FINDING A SOLUTION

The 7 th Balan Conference on Operational Research BACOR 5 Constanta, May 5, Roania OPTIMAL TIME AND SPACE COMPLEXITY ALGORITHM FOR CONSTRUCTION OF ALL BINARY TREES FROM PRE-ORDER AND POST-ORDER TRAVERSALS

### Bhakta Kavi Narsinh Mehta University, Junagadh

Bhakta Kavi Narsinh Mehta University, Junagadh Draft Syllabus for B.Sc. (Computer Science) Bachelor of Science (Computer Science) (Semester - 1) Effective From June - 2016 B.Sc. (C.S.) (Semester - 1) CS-101:

### A binary heap is a complete binary tree, where each node has a higher priority than its children. This is called heap-order property

CmSc 250 Intro to Algorithms Chapter 6. Transform and Conquer Binary Heaps 1. Definition A binary heap is a complete binary tree, where each node has a higher priority than its children. This is called

### Lecture 12 Doubly Linked Lists (with Recursion)

Lecture 12 Doubly Linked Lists (with Recursion) In this lecture Introduction to Doubly linked lists What is recursion? Designing a node of a DLL Recursion and Linked Lists o Finding a node in a LL (recursively)

### Physical Data Organization

Physical Data Organization Database design using logical model of the database - appropriate level for users to focus on - user independence from implementation details Performance - other major factor

### 2. Compressing data to reduce the amount of transmitted data (e.g., to save money).

Presentation Layer The presentation layer is concerned with preserving the meaning of information sent across a network. The presentation layer may represent (encode) the data in various ways (e.g., data

### Binary Search Trees > = Binary Search Trees 1. 2004 Goodrich, Tamassia

Binary Search Trees < 6 2 > = 1 4 8 9 Binary Search Trees 1 Binary Search Trees A binary search tree is a binary tree storing keyvalue entries at its internal nodes and satisfying the following property:

### DATABASE DESIGN - 1DL400

DATABASE DESIGN - 1DL400 Spring 2015 A course on modern database systems!! http://www.it.uu.se/research/group/udbl/kurser/dbii_vt15/ Kjell Orsborn! Uppsala Database Laboratory! Department of Information

### Unit 1. 5. Write iterative and recursive C functions to find the greatest common divisor of two integers. [6]

Unit 1 1. Write the following statements in C : [4] Print the address of a float variable P. Declare and initialize an array to four characters a,b,c,d. 2. Declare a pointer to a function f which accepts

### Data Structures, Practice Homework 3, with Solutions (not to be handed in)

Data Structures, Practice Homework 3, with Solutions (not to be handed in) 1. Carrano, 4th edition, Chapter 9, Exercise 1: What is the order of each of the following tasks in the worst case? (a) Computing

### Efficiency of algorithms. Algorithms. Efficiency of algorithms. Binary search and linear search. Best, worst and average case.

Algorithms Efficiency of algorithms Computational resources: time and space Best, worst and average case performance How to compare algorithms: machine-independent measure of efficiency Growth rate Complexity

### Lecture Notes on Binary Search Trees

Lecture Notes on Binary Search Trees 15-122: Principles of Imperative Computation Frank Pfenning André Platzer Lecture 17 October 23, 2014 1 Introduction In this lecture, we will continue considering associative

### Catalan Numbers. Thomas A. Dowling, Department of Mathematics, Ohio State Uni- versity.

7 Catalan Numbers Thomas A. Dowling, Department of Mathematics, Ohio State Uni- Author: versity. Prerequisites: The prerequisites for this chapter are recursive definitions, basic counting principles,

### Outline BST Operations Worst case Average case Balancing AVL Red-black B-trees. Binary Search Trees. Lecturer: Georgy Gimel farb

Binary Search Trees Lecturer: Georgy Gimel farb COMPSCI 220 Algorithms and Data Structures 1 / 27 1 Properties of Binary Search Trees 2 Basic BST operations The worst-case time complexity of BST operations