# Course: Programming II - Abstract Data Types. The ADT Binary Tree

Save this PDF as:

Size: px
Start display at page:

## Transcription

1 The ADT Binary Tree The Binary Tree is a more general ADT than the linear list: it allows one item to have two immediate successors. Definition The ADT Binary Tree is a finite set of nodes which is either empty or consists of a data item (called the root) and two disjoint binary trees (called the left and right subtrees of the root), together with a number of access procedures. r T L data item T R r = a node T L = left binary tree T R = right binary tree Applications representing 1:2 relations; representing sets; evaluating expressions. Nodes with no successors are called leaves. The roots of the left and right subtrees of a node i are called the children of i ; the node i is their parent; they are siblings. A child has one parent. A parent has at most two children. The ADT Binary Tree Slide Number 1 The data organisations presented so far are linear in that items are one after another. The Binary Tree is a more general form of ADT, in which data are organised in a non linear, hierarchical form whereby one item can have more than one immediate successor. A Binary Tree is a position-oriented ADT, as lists, stacks, queues. However, since it is not linear as the ADT lists we have seen so far, we will not reference items in a binary tree by using a position number. The Binary Search Tree is a value-oriented ADT whose elements are organised on the basis of their values. All trees are hierarchical in nature. Intuitively, hierarchical means that a parent-child relationship exists between the nodes in the tree. If there is a link between a node n and a node m, and n is above node m in the tree, then n is the parent of m, and node m is a child of n. Children of the same parent are called siblings. Each node in a tree has at most one parent, and exactly one node, called the root of the tree, has no parent. A node that has no children is called a leaf of the tree. The parent-child relationship between the nodes can be generalised to the relationships ancestor and descendant. The root of a tree is an ancestor of every node in the tree. A subtree in a tree is any node in the tree together with all its descendants. A subtree of a node r is a subtree rooted at a child of the node r. To give a formal definition of what a tree is, we say that a binary tree is a set of node which is either empty, or is partitioned into three disjoint subsets: (i) a single node r, the root; and (ii) two (possibly empty) sets that are binary trees, called the left and the right subtrees of r. Each node in a binary tree has therefore no more than two children. You have already seen uses of binary trees in the logic course. These are the trees used to define if a logical expression is a well-formed formula of propositional logic or predicate logic. Evaluation of expressions is a typical application of binary trees. The nodes of a tree are all of the same type. We still assume the type to be Object (in general). 1

2 Example of Binary Tree Rector Root Dean of Science Siblings Dean of Engineering Head of Maths Head of Physics Head of Civil Eng Head of Mech Eng Leaves The ADT Binary Tree Slide Number 2 2

3 Access Procedures Constructor operations to construct a Tree: i. createemptytree( ) // post: creates an empty tree ii. createbtree(rootitem) // post: creates a one-node binary tree whose root contains rootitem. Predicate operations to test Trees i. isempty( ) // post: determines whether a tree is empty Selector operations to select items of a Tree i. getrootitem( ) // post: retrieves the data item in the root of a non-empty binary tree. The ADT Binary Tree Slide Number 3 This slide provides basic access procedures for general binary trees. Additional access procedures are given in the next slide. What we have here are just the procedures related to the root of a tree, and the creation of a tree. Note that in the case of trees, we can either create an empty tree, or also create just a single node tree, or (as shown in the next slide) create a tree by passing a root item and the two sub-trees. The implementation of general binary trees can be quite complex. We will therefore introduce example implementations for general binary trees only for some of the access procedures. We will instead concentrate on, and show in more detail in the next lecture, a particular type of binary tree, called a binary search tree. Procedures are again defined here only in terms of their main post-conditions. Exceptions cases need to be included as part of the post-conditions for some of these procedures, as we will explain in the next slide. 3

4 Additional Access Procedures createbtree(rootitem, lefttree, righttree) // post: creates a binary tree whose root contains rootitem, and has lefttree and // righttree, respectively, as its left and right subtrees. attachleft(newitem) // post: Attaches a left child containing newitem to the root of a binary tree attachright(newitem) // post: Attaches a right child containing newitem to the root of a binary tree attachleftree(lefttree) // post: Attaches lefttree as the left subtree of the root of a binary tree. attachrighttree(righttree) // post: Attaches righttree as the right subtree of the root of a binary tree. detachleftsubtree( ) // post: detaches and returns the left subtree of a binary tree s root. detachrightsubtree( ) // post: detaches and returns the right subtree of a binary tree s root. The ADT Binary Tree Slide Number 4 This slide provides the remaining access procedures for general binary trees. These procedures are defined here only in terms of their main post-conditions. Exception cases need to be included as part of the post-conditions to all but the first access procedure given here. The circumstances for exception are when the tree is empty, as for each of these procedures there will be no root node to attach left/right children or left/right subtrees. Note that two other access procedures might be useful in managing binary trees. These are getrightsubtree, and getleftsubtree, which respectively return the left and right subtree of a binary tree s root without modifying the tree. 4

5 Axioms for ADT Tree These are only some of the axioms the access procedures have to satisfy, where Item is an item, atree, LTree and RTree are given Trees: 1. (atree.createtree( ) ).isempty = true 2. (atree.createbtree(item, LTree, RTree)).isEmpty() = false 3. (atree.createtree( )).getrootitem( ) = error 4. (atree. createbtree(item, LTree, RTree)). getrootitem( ) = Item 5. (atree.createtree( )).detachleftsubtree( ) = error 6. (atree.createbtree(item, LTree, RTree)). detachleftsubtree( ) = LTree 7. (atree.createtree( )).detachrightsubtree( ) = error 8. (atree.createbtree(item, LTree, RTree)). detachrightsubtree( ) = RTree The ADT Binary Tree Slide Number 5 In this slide I have listed some of the main axioms that the access procedures for an ADT binary tree have to satisfy. Note that, the procedures for constructing a tree are also attachleft, attachright, attachleftsubtree, attachrightsubtree. A full axiomatic definition of binary search trees will also need to include axioms for the access procedures given in this slide, but applied to a binary tree constructed by applying these other constructor operations. 5

6 Additional Definitions 1. A path of a tree T to a subtree T k is the sequence T 1, T 2,, T k of trees, where for each 1 i < k, T i+1 = T i.detachleftsubtree or T i+1 = T i.detachrightsubtree. 2. The height of a tree is defined as height(t.createtree( ) ) = 0; height(t.createbtree(item,ltree,rtree)) = 1+ max(height(ltree),height(rtree)); 3. Shortest Path in a tree is defined as ShortestPath(T.createTree( )) = 0 ShortestPath(T.createBTree(Item,LTree,RTree)) = 1+ min((shortestpath(ltree),shortestpath(rtree)); 4. A perfectly balanced tree (or full) is a tree whose height and its shortest path have the same value. The ADT Binary Tree Slide Number 6 Trees come in many shapes. Two given trees might be different from each other even though they might contain the same number of nodes. The height of a tree is the number of nodes on the longest path from the root to a leaf. A different definition of height could be considered which uses recursion. This is the definition given in this slide. A perfectly balanced tree (or full tree) of height h is a tree in which every node that is at a level less than h has two children. This means that each node has left and right subtrees of the same height. In terms of number of leaves, among all binary tree of height h, a full binary tree is a tree with as many leaves as possible and all the leaves are at the same level in the tree. An equivalent characterisation is given in this slide. A perfectly balanced tree is a tree whose height and shortest path have the same value. 6

7 Theorem The number of nodes in a perfectly balanced tree of height h ( 0) is 2 h - 1 nodes. Proof The proof is by induction on h: Base Case: h=0. Empty tree is balanced; = 0; Inductive Hypothesis: suppose the theorem holds for k, with 0 k h. In this case a perfectly balanced tree has 2 k 1 nodes. We want to show it holds for a perfectly balanced tree with height k+1. A perfectly balanced tree of height k+1 consists of a root node and 2 subtrees each of height k. Total number of nodes is: (2 k 1) (2 k 1) = = 2*2 k 1 = 2 k+1 1 So a perfectly balanced tree of height h has 2 h - 1 nodes The ADT Binary Tree Slide Number 7 7

8 Additional Definitions (continued) A perfectly balanced tree with n nodes has a height of h = log 2 (n+1) eg.: for n=7 Rector Rector Head of Maths Dean of Science Head of Physics Head of Civ Eng A perfectly balanced tree Dean of Eng. Head of Mech Eng Dean Head of Dept Student A Skewed Tree (or degenerate tree) Definitions: The level of a node is 1 if the node is the root of the tree; otherwise it is defined to be 1 more than the level of its parent. A complete tree of height h is a tree which is full down to level h-1, with level h filled in from left to right. The ADT Binary Tree Slide Number 8 This slide completes the set of definitions of main features of binary trees. In particular, we have seen in the previous slide a theorem that proves the relation between the height of a full (or perfectly balanced) binary tree and its nodes. This relation can be used also to define the height of a given full tree composed of a given number of nodes. We have also given here an example of a full tree. Another type of tree is the skewed tree, which is essentially a linked list, as shown in this slide. Other important definitions on trees is that of level of a node and that of complete tree. A level of a node is a recursive definition, which assigns value 1 to the root node and assigns value = (1+ level of its parent node) to any node that is not a root node. A complete binary tree is a particular type of tree. We normally say that a binary tree is a complete tree of height h, if it is a perfectly balanced tree of height h-1, and its nodes at level h are completed started from left to right. What does this mean exactly? The fact that it s perfectly balanced of height h-1, means that all its nodes with level less than h-1 have two children. So the nodes with level h-1 may or may not have children. However, if a node with level h-1 has children, then all nodes to its left with the same level must have two children each, and if in particular it has only one child then it must be its left child. I ve given here an example of a complete tree of height 3: Pam Sue Mary Ellen April 8

9 Tree Traversals Methods for visiting each node of a tree. Given the recursive definition of a binary tree, we could think of using a recursive traversal algorithm: pseudocode T L r data item T R traverse(binarytree) if (binarytree is not empty) { traverse(left subtree of binarytree s root); traverse(right subtree of binarytree s root); } Not complete: it doesn t include When shall we visit the root node r? operation for visiting the root r visit r before traversing both r s subtrees; visit r after it has traversed r s left subtree; but before traversing r s right subtree visit r after it has traversed both of r s subtrees. The ADT Binary Tree Slide Number 9 Programs that use tree structures often need to visit and process each node of a given tree. Methods for traversing or visiting each node of a tree are called tree traversals. For example, suppose that we have a tree where each node contains an integer, and we want to print a list of all the integers in the tree. Then for the purpose of this example, we can assume that visiting a node simply means displaying the data portion of the node. With the recursive definition of a binary tree in mind, we can construct a recursive traversal algorithm as shown in this slide. A binary tree is in fact either empty or it is of the form root node r, left sub-tree and right sub-tree as shown in the slide. If the tree is empty, then the traversal algorithm is not supposed to take any action (empty tree would therefore be the base case of our algorithm). If the tree is not empty, the traversal algorithm must perform three tasks: visit the root node, traverse the left sub-tree and right sub-tree of the root node. The general form of a traversal algorithm should therefore be as shown above in pseudocode. However, the algorithm given here is not complete as it does not include any operation on (or visiting) the root node r (which in the recursive execution means operation for visiting each node of the tree). We can have three choices, given the form of traversal algorithm sketched here: 1) we could visit the root node r before the algorithm traverses both of r s subtrees; 2) we could visit the root node r after the algorithm has traversed r s left subtree but before traversing r s right subtree; 3) we could visit the root node r after the algorithm has traversed both of r s subtrees. These three different ways correspond to three different traversal algorithms for binary trees, called respectively pre-order, in-order and post-order traversal, which are defined in the next slide. 9

10 Pre-order: Visit the root node before traversing the subtrees preorder(binarytree) if (binarytree is not empty) { Display the data in the root node; preorder(left subtree of binarytree s root); preorder(right subtree of binarytree s root); } In-order: Visit the root after traversing left sub-tree and before right sub-tree. inorder(binarytree) if (binarytree is not empty) {inorder(left subtree of binarytree s root); Display the data in the root node; inorder(right subtree of binarytree s root); } Post-order: Visit the root after traversing left sub-tree and before right sub-tree. postorder(binarytree) if (binarytree is not empty) {postorder(left subtree of binarytree s root); postorder(right subtree of binarytree s root); Display the data in the root node; } The ADT Binary Tree Slide Number 10 The three different choices of when to visit the root node give rise to three different traversal algorithms. The pre-order traversal is when the root node is visited first before its left sub-tree and right sub-tree are processed (or traversed). This is why in the pseudocode given here the operation Display the data in the root node is performed before the two recursive calls of preorder. The order of access is this case would be root, left, right. The in-order traversal is when the root node is visited after the root s left sub-tree has been visited and before the root s right sub-tree is traversed. This is why in the pseudocode given here the operation Display the data in the root node is performed between the two recursive calls of inorder. The order of access is this case would be left, root, right. The post-order traversal is when the root node is visited after the root s left and right sub-trees have been visited. In this case, the operation Display the data in the root node is performed after the two recursive calls of postorder. The order of access is this case would be left, right, root. 10

11 Examples: Course: Programming II - Abstract Data Types Display the nodes of the tree: Pre-order: 14, 17, 9, 53, 30, 50, 11; In-order: 9, 17, 30, 53, 50, 14, 11; Post-order: 9, 30, 50, 53, 17, 11, 14; Tree representation of the algebraic expression: (a+(b-c))*d. Display the nodes of the tree: Pre-order: * + a b c d. This gives the prefix notation of expressions; In-order: a + b c * d This requires bracketing for representing sub-expressions. It is called infix notation of expressions; Post-order: a b c - + d * This gives the postfix notation of expressions. * + d a - The ADT Binary Tree Slide Number 11 b c Here we show two examples of tree traversal. Our second example is a tree representation of an algebraic expression. Traversing the tree in pre-order gives a sequence that is called prefix notation of a given algebraic expression, where the operators precede their operands. Traversing the tree in inorder gives a sequence called the infix notation of an algebraic expression, which however needs bracketing in order to preserve the fact that subtrees are sub expressions of the given one. Finally, traversing the tree in postorder gives a sequence called postfix notation, where operators appear after the operands. Note that infix notation, although conventional, is inconvenient for automatic execution, because: - brackets may be needed to clarify expressions - the order in which the operators/operands are required is not the order in which they appear. 11

12 Depth-first and Breadth-first traversals Pre-order, in-order, and post-order tree traversals are depth-first traversals, as (except for the root in pre-order) nodes further away from the root node (i.e.deepest nodes) are visited first. Recursive algorithms: the run-time implementation of recursion keeps track of the progress through the tree. Iterative algorithms: must keep track of higher-level nodes explicitly, for example, using a stack. Nodes can be pushed during progress away from the root, and can be popped to move back towards the root. Breadth-first traversal visits all the nodes at one level, before moving to another level. Root first, then the child nodes of the root, then the children of the children in the order in which the root s children were visited. A queue of children of a node must be built 14 Breadth-first: 14, 17, 11, 53, 30, 50 up when the node is visited, so that the correct ordering is maintained at the next level The ADT Binary Tree Slide Number 12 12

13 A Static Implementation of Complete Trees 3 1 Advantages: Sue 0 Pam 4 5 Ellen April Sara Mary tree[i] = node numbered i 2 Pam Sue Mary Ellen April Sara tree[ ] 1. Data from the root always appears in the [0] position of the array; 2. Suppose that a non-root node appears at position [i]. Then its parent node is always at location [(i-1)/2] (using integer division). 3. Suppose that a node appears at position [i] of the array. Then its children (if they exist) always appear at locations [2i+1] for the left child and location [2i+2] for the right child. The ADT Binary Tree Slide Number 13 For all the ADTs considered so far in this part of the course, we have provided a definition of the interface for the ADT, which defines the access procedures for the ADT, and various classes that implement this interface as example implementations (e.g., static and dynamic implementation of an ADT). In the case of trees, we have seen so far that we can have different types of trees and that more specific access procedures might be useful for some type of trees but not for others. It is therefore more difficult to present example implementation of binary trees using this same distinction (basic interface and different implementation classes). We will still see, however, examples of static vs dynamic implementation of binary trees. As for static implementation, we consider here the case of array-based implementation of just complete binary trees, since this implementation is easier when the binary tree is complete. In a complete tree, all the levels are full except maybe for the lowest level. At the lowest level, the nodes are as far left as possible. The whole tree can be stored in a simple array, starting by storing the root s item in the [0] location of the array, then taking the two nodes at the next level in the tree and placing them left node first into the array at locations [1] and [2] respectively, and continuing in this way until all the nodes have been stored in the array. The simple representation is due to the fact that the tree is a complete tree, and therefore we have define specific formulae for accessing in the array to the parent (or children) node(s) of a given node. These formulae are given in this slide. They also make it easy to implement algorithms for traversing the tree. A class TreeArrayBased will then have at least two private instance variables: (a) the array itself, and (b) a second instance variable that keeps track of how much of the array is used (eg.int free = 6). The actual links between the nodes are not stored. Instead, they exist via the formulas given in this slide, which determine where an element (child or parent of a node) is stored in the array based on the element position in the tree. Non complete binary trees could also be implemented using an array, but the array data structure is more complex than the one given here, since it is necessary to keep explicit reference to the children of a node when and if they exist

14 Dynamic implementation of Trees left root item right Data structure class TreeNode{ private Object item; private TreeNode left; private TreeNode right; } class BinaryTree{ private TreeNode root; } left item right left item right public class BinaryTree{ private TreeNode root; public BinaryTree( ){ root = null; } //end default constructor; Creates an empty binary tree. The ADT Binary Tree Slide Number 14 A binary tree can be represented by its individual nodes, where each node is an object of a new binary tree node class, similar to the class node used for the linked lists, etc.the basic idea in a dynamic implementation of a binary tree is that each node of the tree can be stored as an object of a class called TreeNode. This class contains private instance variables that reference other nodes in the tree. Since these variables are private the class Node should also include access procedures for getting or for changing the values of the attributes of a node. We ll see in the next slide the full implementation of the class TreeNode. The entire tree is represented as a reference to the root node. If the tree is empty, the root is null. The constructor BinaryTree( ) given here implements the access procedure createemptytree( ) given in slide 3. In the next slide we see the basic methods of the class TreeNode and some example implementations of other access procedures for the ADT binary tree. 14

15 The class TreeNode Course: Programming II - Abstract Data Types public TreeNode(Object newitem, TreeNode leftchild, TreeNode rightchild){ item = newitem; left = leftchild; right = rightchild; }// end constructor. Getting and setting data and links: public Object getitem( ) // returns the item field of the particular node. public void setitem(object newitem ) //Sets the item field to the new value newitem; public TreeNode getleft( ) // returns the reference to the left child; public TreeNode setleft(treenode leftchild) // sets the left reference to leftchild; public TreeNode getright( ) // returns the reference to the // right child; public void setright(treenode rightchild) //Sets the right reference to rightchild; The ADT Binary Tree Slide Number 15 This slide provides the list of the basic methods that a class TreeNode should have, in terms of their respective post-conditions. Other constructors could also be defined, which for instance, create a TreeNode with just the item and no children. How would you implement such a constructor? Given this new class for binary tree nodes, how would we implement the access procedures for a binary tree? As shown in the previous slide we would need a class called BinaryTree, which includes just the instance variable root, which refers to the root node of the entire tree. Some example implementations of some access procedures for the BinaryTree class are given in the next slide. 15

16 Some Methods of the Class BinaryTree (1) public BinaryTree(Object rootitem){ root = new TreeNode(rootItem, null, null); }// end constructor. public boolean isempty( ){ return root = = null; }// end isempty public Object getrootitem( ) throws TreeException{ if (root = = null){ throw new TreeException( TreeException: Empty tree ); } else {return root.getitem( ); } }// end getrootitem public void attachleft(object newitem) throws TreeException{ if (!isempty() && root.getleft( ) = = null){ root.setleft(new TreeNode(newItem, null, null)); } else { if (isempty( )) {throw new TreeException( TreeException: Empty tree ); } } }// end attachleft The ADT Binary Tree Slide Number 16 In some previous slide we have given a default constructor for the class BinaryTree that is supposed to create an empty binary tree. Other constructors can be defined, for instance, to create a binary tree with just one node (an example implementation is given at the top of this slide), or to create a tree from a reference to a root node (an example implementation is given on the top of the next slide). This last type of constructor could be very useful to define implementations of other access procedures, as shown. If used as an auxiliary constructor, it should be defined as protected in order to prevent client classes from using it directly. This is because client classes are in general not able to access node references directly, as node references are private to the class BinaryTree. In the implementation of the access procedure getrootitem we need to check that the binary tree is not empty. If you look at the axioms given in slide 4, the call of this method on an empty tree should flag an error. An example implementation of TreeException can be the following: public class TreeException extends java.lang.runtimeexception { public TreeException(String s){ super(s); }// end constructor }// end TreeException An example implementation is also given for the access procedure getlefttree. This is supposed to return the left subtree of a binary tree s root. To do so, we could use the protected constructor of BinaryTree and create a new binary tree that has the root s left node as its root node. What would the implementation of the access procedure getrighttree look like? This is left as exercise. 16

17 Some Methods of the Class BinaryTree (2) protected BinaryTree(TreeNode rootnode){ root = rootnode; }// end protected constructor public BinaryTree detachleftsubtree( ) throws TreeException{ if (isempty( )) {throws new TreeException( TreeException: Empty tree ); } else {BinaryTree lefttree; lefttree = new BinaryTree(root.getLeft( )); root.setleft(null); return lefttree; } }// end getlefttree public BinaryTree attachleftsubtree(binarytree lefttree) throws TreeException{ if (isempty( )) {throws new TreeException( TreeException: Empty tree ); } else { if (root.getleft()!= null){throws new TreeException( Left subtree already exists );} else { root.setleft(lefttree.root); lefttree.makeempty( ); } }// end attachleftsubtree The ADT Binary Tree Slide Number 17 In this slide we give other example implementations of access procedures for a binary tree. Note that in the implementation of attachleftsubtree we have used a method makeempty(). This can be defined as an auxiliary method for the class BinaryTree, which empties a given tree, by just setting its root node equal to null. In our example here, the use of lefttree.makeempty( ) is in order to guarantee that the left tree passed as parameter to the method attachleftsubtree is now only referenced by the root node of the tree. The remaining methods of the class BinaryTree can be implemented in a way similar to that shown in these last two slides. It is therefore left to you as a little exercise. 17

18 Summary Binary trees provide a hierarchical organisation of data, important in applications The implementation of a binary tree is usually reference based. If the tree is complete, an efficient array-based implementation is possible. Traversing a tree is a useful operation; intuitively, it means to visit every node in the tree. The ADT Binary Tree Slide Number 18 18

### The ADT Binary Search Tree

The ADT Binary Search Tree The Binary Search Tree is a particular type of binary tree that enables easy searching for specific items. Definition The ADT Binary Search Tree is a binary tree which has an

### Full and Complete Binary Trees

Full and Complete Binary Trees Binary Tree Theorems 1 Here are two important types of binary trees. Note that the definitions, while similar, are logically independent. Definition: a binary tree T is full

### 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 (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

### 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

### 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

### 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 Structure with C

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

### 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

### 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

### 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

### 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:

### 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

### 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:

### 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

### 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

### 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

### GRAPH THEORY LECTURE 4: TREES

GRAPH THEORY LECTURE 4: TREES Abstract. 3.1 presents some standard characterizations and properties of trees. 3.2 presents several different types of trees. 3.7 develops a counting method based on a bijection

### 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

### 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

### Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

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

### Object Oriented Software Design

Object Oriented Software Design Inner classes, RTTI, Tree implementation Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 29, 2010 G. Lipari (Scuola Superiore Sant

### 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,

### 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

### 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

### 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)

### 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

### 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

### 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

### 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

### Data Structures and Algorithms V22.0102. Otávio Braga

Data Structures and Algorithms V22.0102 Otávio Braga We use a stack When an operand is read, output it When an operator is read Pop until the top of the stack has an element of lower precedence Then push

### Stacks. The stack ADT Stack Implementation. Stack Examples. using arrays using generic linked lists using List ADT. EECS 268 Programming II 1

Stacks The stack ADT Stack Implementation using arrays using generic linked lists using List ADT Stack Examples 1 Stacks and Queues Linear data structures each item has specific first, next, and previous

### 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.204 Lecture 6. Data structures: stacks, queues, trees, dictionaries. Data structures

1.204 Lecture 6 Data structures: stacks, queues, trees, dictionaries Data structures Correct and efficient representation of data and applicable rules Stack: last in, first out discipline Queue: first

### 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

### 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

### 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

### Data Structures Fibonacci Heaps, Amortized Analysis

Chapter 4 Data Structures Fibonacci Heaps, Amortized Analysis Algorithm Theory WS 2012/13 Fabian Kuhn Fibonacci Heaps Lacy merge variant of binomial heaps: Do not merge trees as long as possible Structure:

### 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

### Intro. to the Divide-and-Conquer Strategy via Merge Sort CMPSC 465 CLRS Sections 2.3, Intro. to and various parts of Chapter 4

Intro. to the Divide-and-Conquer Strategy via Merge Sort CMPSC 465 CLRS Sections 2.3, Intro. to and various parts of Chapter 4 I. Algorithm Design and Divide-and-Conquer There are various strategies we

### 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,

### Binary Trees (1) Outline and Required Reading: Binary Trees ( 6.3) Data Structures for Representing Trees ( 6.4)

1 Binary Trees (1) Outline and Required Reading: Binary Trees ( 6.3) Data Structures for Representing Trees ( 6.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic Binary Tree 2 Binary Tree tree with

### Exam study sheet for CS2711. List of topics

Exam study sheet for CS2711 Here is the list of topics you need to know for the final exam. For each data structure listed below, make sure you can do the following: 1. Give an example of this data structure

### Data Structures. September 28

Data Structures September 28 1 Hierachicalstructures: Trees 2 Objectives Discuss the following topics: Trees, Binary Trees, and Binary Search Trees Implementing Binary Trees Tree Traversal Searching a

### 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

### 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

### 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

### 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

### 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

### 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

### 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

### Tree Properties (size vs height) Balanced Binary Trees

Tree Properties (size vs height) Balanced Binary Trees Due now: WA 7 (This is the end of the grace period). Note that a grace period takes the place of a late day. Now is the last time you can turn this

### In our lecture about Binary Search Trees (BST) we have seen that the operations of searching for and inserting an element in a BST can be of the

In our lecture about Binary Search Trees (BST) we have seen that the operations of searching for and inserting an element in a BST can be of the order O(log n) (in the best case) and of the order O(n)

### 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

### 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

### Data Structures Using C++ 2E. Chapter 5 Linked Lists

Data Structures Using C++ 2E Chapter 5 Linked Lists Doubly Linked Lists Traversed in either direction Typical operations Initialize the list Destroy the list Determine if list empty Search list for a given

### 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

### 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

### Comp 245 Data Structures. Stacks

Comp 245 Data Structures Stacks What is a Stack? A LIFO (last in, first out) structure Access (storage or retrieval) may only take place at the TOP NO random access to other elements within the stack An

### Mathematical Induction. Lecture 10-11

Mathematical Induction Lecture 10-11 Menu Mathematical Induction Strong Induction Recursive Definitions Structural Induction Climbing an Infinite Ladder Suppose we have an infinite ladder: 1. We can reach

### Operations: search;; min;; max;; predecessor;; successor. Time O(h) with h height of the tree (more on later).

Binary search tree Operations: search;; min;; max;; predecessor;; successor. Time O(h) with h height of the tree (more on later). Data strutcure fields usually include for a given node x, the following

### 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.

### CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 221] edge. parent

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 221] Trees Important terminology: edge root node parent Some uses of trees: child leaf model arithmetic expressions and other expressions

### COMPUTER SCIENCE. Paper 1 (THEORY)

COMPUTER SCIENCE Paper 1 (THEORY) (Three hours) Maximum Marks: 70 (Candidates are allowed additional 15 minutes for only reading the paper. They must NOT start writing during this time) -----------------------------------------------------------------------------------------------------------------------

### Class Notes CS 3137. 1 Creating and Using a Huffman Code. Ref: Weiss, page 433

Class Notes CS 3137 1 Creating and Using a Huffman Code. Ref: Weiss, page 433 1. FIXED LENGTH CODES: Codes are used to transmit characters over data links. You are probably aware of the ASCII code, a fixed-length

### Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * *

Binary Heaps A binary heap is another data structure. It implements a priority queue. Priority Queue has the following operations: isempty add (with priority) remove (highest priority) peek (at highest

### 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

### 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,

### 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

### The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

The Tower of Hanoi Recursion Solution recursion recursion recursion Recursive Thinking: ignore everything but the bottom disk. 1 2 Recursive Function Time Complexity Hanoi (n, src, dest, temp): If (n >

### 3. Mathematical Induction

3. MATHEMATICAL INDUCTION 83 3. Mathematical Induction 3.1. First Principle of Mathematical Induction. Let P (n) be a predicate with domain of discourse (over) the natural numbers N = {0, 1,,...}. If (1)

### Data Structures Using Java

Data Structures Using Java D. S. Malik P. S. Nair THOMSON COURSE TECHNOLOGY Australia Canada Mexico Singapore Spain United Kingdom United States TABLE OF Contents PREFACE XXV 1.Software Engineering Principles

### Chapter 3. Cartesian Products and Relations. 3.1 Cartesian Products

Chapter 3 Cartesian Products and Relations The material in this chapter is the first real encounter with abstraction. Relations are very general thing they are a special type of subset. After introducing

### 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

### 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

### CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team Lecture Summary In this lecture, we learned about the ADT Priority Queue. A

### Sequential Data Structures

Sequential Data Structures In this lecture we introduce the basic data structures for storing sequences of objects. These data structures are based on arrays and linked lists, which you met in first year

### 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

### Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

Stacks (and Queues) 1 Stacks Stack: what is it? ADT Applications Implementation(s) 2 CSCU9A3 1 Stacks and ueues A stack is a very important data structure in computing science. A stack is a seuence of

### 6.3 Conditional Probability and Independence

222 CHAPTER 6. PROBABILITY 6.3 Conditional Probability and Independence Conditional Probability Two cubical dice each have a triangle painted on one side, a circle painted on two sides and a square painted

### Analysis of a Search Algorithm

CSE 326 Lecture 4: Lists and Stacks 1. Agfgd 2. Dgsdsfd 3. Hdffdsf 4. Sdfgsfdg 5. Tefsdgass We will review: Analysis: Searching a sorted array (from last time) List ADT: Insert, Delete, Find, First, Kth,

### 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

### Algorithms and Data S tructures Structures Stack, Queues, and Applications Applications Ulf Leser

Algorithms and Data Structures Stack, Queues, and Applications Ulf Leser Content of this Lecture Stacks and Queues Tree Traversal Towers of Hanoi Ulf Leser: Alg&DS, Summer semester 2011 2 Stacks and Queues

### 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

### 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

### Structural Design Patterns Used in Data Structures Implementation

Structural Design Patterns Used in Data Structures Implementation Niculescu Virginia Department of Computer Science Babeş-Bolyai University, Cluj-Napoca email address: vniculescu@cs.ubbcluj.ro November,

### Java Software Structures

INTERNATIONAL EDITION Java Software Structures Designing and Using Data Structures FOURTH EDITION John Lewis Joseph Chase This page is intentionally left blank. Java Software Structures,International Edition

### 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)

### Chapter 3: Restricted Structures Page 1

Chapter 3: Restricted Structures Page 1 1 2 3 4 5 6 7 8 9 10 Restricted Structures Chapter 3 Overview Of Restricted Structures The two most commonly used restricted structures are Stack and Queue Both

### CompSci-61B, Data Structures Final Exam

Your Name: CompSci-61B, Data Structures Final Exam Your 8-digit Student ID: Your CS61B Class Account Login: This is a final test for mastery of the material covered in our labs, lectures, and readings.

### 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:

### Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

Outline Computer Science 1 Stacks Mike Jacobson Department of Computer Science University of Calgary Lecture #12 1 2 Applications Array-Based Linked List-Based 4 Additional Information Mike Jacobson (University

### Lecture 1: Course overview, circuits, and formulas

Lecture 1: Course overview, circuits, and formulas Topics in Complexity Theory and Pseudorandomness (Spring 2013) Rutgers University Swastik Kopparty Scribes: John Kim, Ben Lund 1 Course Information Swastik

### 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

### 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,

### Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Class Overview CSE 326: Data Structures Introduction Introduction to many of the basic data structures used in computer software Understand the data structures Analyze the algorithms that use them Know

### 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