Algorithms and data structures Protected by 14.9.2015.

Slides:



Advertisements
Similar presentations
Algorithms and data structures Protected by
Advertisements

Algorithms and data structures
S. Sudarshan Based partly on material from Fawzi Emad & Chau-Wen Tseng
Senem Kumova Metin Spring2009 BINARY TREES && TREE TRAVERSALS Chapter 10 in A Book on C.
Algorithms and data structures Protected by
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Binary Trees Chapter 6. Linked Lists Suck By now you realize that the title to this slide is true… By now you realize that the title to this slide is.
Computer Science C++ High School Level By Guillermo Moreno.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
Fall 2007CS 2251 Trees Chapter 8. Fall 2007CS 2252 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information.
Trees, Binary Trees, and Binary Search Trees COMP171.
Data Structures Data Structures Topic #8. Today’s Agenda Continue Discussing Table Abstractions But, this time, let’s talk about them in terms of new.
Lec 15 April 9 Topics: l binary Trees l expression trees Binary Search Trees (Chapter 5 of text)
© 2006 Pearson Addison-Wesley. All rights reserved11 A-1 Chapter 11 Trees.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Data Structures and Algorithms Session 13 Ver. 1.0 Objectives In this session, you will learn to: Store data in a tree Implement a binary tree Implement.
Bioinformatics Programming 1 EE, NCKU Tien-Hao Chang (Darby Chang)
Trees Chapter 15 Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
CS Data Structures Chapter 15 Trees Mehmet H Gunes
CS Data Structures Chapter 5 Trees. Chapter 5 Trees: Outline  Introduction  Representation Of Trees  Binary Trees  Binary Tree Traversals 
Trees EENG212 Algorithms and Data Structures. Trees Outline  Introduction to Trees  Binary Trees: Basic Definitions  Traversing Binary Trees  Node.
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 10: Trees Data Abstraction & Problem Solving with C++
1 CSE 1342 Programming Concepts Trees. 2 Basic Terminology Trees are made up of nodes and edges. A tree has a single node known as a root. –The root is.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
1 Trees A tree is a data structure used to represent different kinds of data and help solve a number of algorithmic problems Game trees (i.e., chess ),
Tree (new ADT) Terminology:  A tree is a collection of elements (nodes)  Each node may have 0 or more successors (called children)  How many does a.
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
Tree Data Structures. Introductory Examples Willliam Willliam BillMary Curt Marjorie Richard Anne Data organization such that items of information are.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 4. Trees.
Trees, Binary Trees, and Binary Search Trees COMP171.
Starting at Binary Trees
Trees  Linear access time of linked lists is prohibitive Does there exist any simple data structure for which the running time of most operations (search,
 Trees Data Structures Trees Data Structures  Trees Trees  Binary Search Trees Binary Search Trees  Binary Tree Implementation Binary Tree Implementation.
TREES. What is a tree ? An Abstract Data Type which emulates a tree structure with a set of linked nodes The nodes within a tree are organized in a hierarchical.
Data Structures TREES.
Algorithms and data structures Protected by
CE 221 Data Structures and Algorithms Chapter 4: Trees (Binary) Text: Read Weiss, §4.1 – 4.2 1Izmir University of Economics.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 240 Recursion and Trees Dale Roberts, Lecturer
Review 1 Queue Operations on Queues A Dequeue Operation An Enqueue Operation Array Implementation Link list Implementation Examples.
Lecture - 10 on Data Structures. 6:05:57 PM Prepared by, Jesmin Akhter, Lecturer, IIT,JU.
1 Chapter 4 Trees Basic concept How tree are used to implement the file system How tree can be used to evaluate arithmetic expressions How to use trees.
Binary Search Trees (BST)
Rooted Tree a b d ef i j g h c k root parent node (self) child descendent leaf (no children) e, i, k, g, h are leaves internal node (not a leaf) sibling.
Tree Data Structures. Heaps for searching Search in a heap? Search in a heap? Would have to look at root Would have to look at root If search item smaller.
Binary Tree.
Chapter 11. Chapter Summary  Introduction to trees (11.1)  Application of trees (11.2)  Tree traversal (11.3)  Spanning trees (11.4)
1 Trees. 2 Trees Trees. Binary Trees Tree Traversal.
Chapter 12 – Data Structures
Trees Chapter 15.
CSCE 210 Data Structures and Algorithms
Binary Trees.
Binary Search Tree (BST)
Trees.
Data Structures & Algorithm Design
ITEC 2620M Introduction to Data Structures
Binary Trees, Binary Search Trees
Ch. 11 Trees 사실을 많이 아는 것 보다는 이론적 틀이 중요하고, 기억력보다는 생각하는 법이 더 중요하다.
Find in a linked list? first last 7  4  3  8 NULL
CE 221 Data Structures and Algorithms
Binary Trees, Binary Search Trees
CE 221 Data Structures and Algorithms
Trees.
Binary Trees.
Tree.
Binary Trees, Binary Search Trees
NATURE VIEW OF A TREE leaves branches root. NATURE VIEW OF A TREE leaves branches root.
Tree (new ADT) Terminology: A tree is a collection of elements (nodes)
Presentation transcript:

Algorithms and data structures Protected by

Creative Commons n You are free to: share — copy and redistribute the material in any medium or format share — copy and redistribute the material in any medium or format adapt — remix, transform, and build upon the material adapt — remix, transform, and build upon the material n Under the following terms: Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use. Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use. NonCommercial — You may not use the material for commercial purposes. NonCommercial — You may not use the material for commercial purposes. ShareAlike — If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original. ShareAlike — If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original. No additional restrictions — You may not apply legal terms or technological measures that legally restrict others from doing anything the license permits. Text copied from Algorithms and data structures, FER Notices: You do not have to comply with the license for elements of the material in the public domain or where your use is permitted by an applicable exception or limitation. No warranties are given. The license may not give you all of the permissions necessary for your intended use. For example, other rights such as publicity, privacy, or moral rights may limit how you use the material. 2 / 31

Trees

Algorithms and data structures, FER Tree properties n Tree is a finite set of nodes with properties: There is a special node called root There is a special node called root The other nodes are divided among k disjunctive subsets T 1..T k, where each of them is a tree. T 1..T k are called subtrees The other nodes are divided among k disjunctive subsets T 1..T k, where each of them is a tree. T 1..T k are called subtrees n Example: a bc d hi ef jk g 4 / 31

Algorithms and data structures, FER Basic terms - I a is the root of the tree a is the root of the tree Degree of the node a is 2 (degree is the Degree of the node a is 2 (degree is the number of subtrees originating from a node, e.g. the node c is of degree 3) The set {h,i,e,f,j,k} is the set of terminal nodes (leaves) The set {h,i,e,f,j,k} is the set of terminal nodes (leaves) Roots of node subtrees are children of that node (e.g. the nodes e,f,g are children of c ), and that node is called parent (e.g. g is the parent of j ). Roots of node subtrees are children of that node (e.g. the nodes e,f,g are children of c ), and that node is called parent (e.g. g is the parent of j ). Similar terms are used for other relationships ( grandparent, siblings, ancestors ) Similar terms are used for other relationships ( grandparent, siblings, ancestors ) a bc d hi ef jk g 5 / 31

Algorithms and data structures, FER Basic terms - II n Degree of a tree is the maximum degree of a node in the tree, in this example 3 n Level of a node is determined from the definition that the root is on the level 1, and that the levels of node children from the level k are k+ 1 n Depth of a tree equals to the maximum level of a node in that tree a bc d hi ef jk g 6 / 31

Algorithms and data structures, FER Recursive trees in nature The largest dragon tree in the world... 7 / 31

Algorithms and data structures, FER Binary tree - I n Binary tree is a tree consisting of none, one or more nodes of the second degree There can be left and/or right subtree of each node There can be left and/or right subtree of each node The terminology introduced for trees applies also to the binary trees The terminology introduced for trees applies also to the binary trees a b c d a b c d hi efg Skewed tree Complete tree 8 / 31

Algorithms and data structures, FER Binary tree - II k-1 2 k-1 +1 i/26 7 ii+1 2 k -2 2 k -1 2k2k2k2k 2 k +1 2i2i+1... Level k k+1 9 / 31

Algorithms and data structures, FER Binary tree - III n It follows from the binary tree definition: The maximum number of nodes on level k is 2 k-1 The maximum number of nodes on level k is 2 k-1 The maximum number of nodes in a binary tree of depth k is 2 k - 1 for k>0 The maximum number of nodes in a binary tree of depth k is 2 k - 1 for k>0 A tree of depth k with 2 k -1 nodes is called full binary tree A tree of depth k with 2 k -1 nodes is called full binary tree A binary tree of depth k with n nodes is complete iff its nodes correspond to the nodes of a full binary tree of depth k numbered from 1 to n A binary tree of depth k with n nodes is complete iff its nodes correspond to the nodes of a full binary tree of depth k numbered from 1 to n – As a consequence, the difference of levels between leaves of a complete tree cannot be larger than one. 10 / 31

Algorithms and data structures, FER Binary tree – static structure array representation n A complete binary tree can be simply represented with one dimensional array, without any data for linking, obeying the rules for trees For simplicity of expressions, array index starts at 1 For simplicity of expressions, array index starts at 1 n Difficult insertion and deletion of nodes is the problem in array representation of the tree, as it may require displacement of many nodes abcde Skewed tree Complete tree abdhpcefgijklmno 11 / 31

Algorithms and data structures, FER Skewed and complete tree Complete tree abdhpcefgijklmno abcde Skewed tree 12 / 31

Algorithms and data structures, FER Binary tree – rules for array representation Rules for a complete binary tree with n nodes, for the i-th node are: Rules for a complete binary tree with n nodes, for the i-th node are: parent ( i )=  i/2  for i  1 ; when i=1, node i is the root and has no parents parent ( i )=  i/2  for i  1 ; when i=1, node i is the root and has no parents left_child ( i )= 2 * i if 2*i  n ;when 2*i>n the node i has no left child left_child ( i )= 2 * i if 2*i  n ;when 2*i>n the node i has no left child right_child ( i )= 2*i+ 1 if 2 *i+ 1  n ; when 2 *i+1>n the node i has no right child right_child ( i )= 2*i+ 1 if 2 *i+ 1  n ; when 2 *i+1>n the node i has no right child n All binary trees might be represented in this way, but the memory use would not be efficient The worst case are skewed trees using only k locations out of 2 k -1 locations allocated for that tree The worst case are skewed trees using only k locations out of 2 k -1 locations allocated for that tree Complete tree abdhpcefgijklmno / 31

Algorithms and data structures, FER Binary tree - dynamic structure representation n The problem is solved using the structure with pointers This structure is often used and it satisfies the majority of requirements This structure is often used and it satisfies the majority of requirements A pointer at the parent can be added A pointer at the parent can be added struct node{ type data; struct node *left_child; struct node *right_child; /* if required: */ struct node *parent; }; a 14 / 31

Algorithms and data structures, FER Skewed tree a b c d root 15 / 31

Algorithms and data structures, FER Complete tree a b d h root c ef i g 16 / 31

Algorithms and data structures, FER k- trees A natural generalisation of binary trees are the k- trees A natural generalisation of binary trees are the k- trees k is the tree degree, k>2, with the same representation possibilities k is the tree degree, k>2, with the same representation possibilities n General trees, having different degrees, can be transformed into binary trees It results with shorter and more efficient algorithms and with less memory requirements It results with shorter and more efficient algorithms and with less memory requirements 17 / 31

Algorithms and data structures, FER Search tree n A search tree can be formed (sorted, ordered tree) according to the key value stored in each node. Insertion of a new node starts with the search from the root of the tree. The key value of the new node is compared with already stored key values: If the key of the new node is smaller than the key of the stored node, the comparisons continue along the left subtree If the key of the new node is smaller than the key of the stored node, the comparisons continue along the left subtree If the key of the new node is larger than the key of the stored node, the comparisons continue along the right subtree If the key of the new node is larger than the key of the stored node, the comparisons continue along the right subtree If the stored node has no subtree in the required direction, the new node becomes a child of the stored node If the stored node has no subtree in the required direction, the new node becomes a child of the stored node  SortiranoStablo (SortedTree) 18 / 31

Algorithms and data structures, FER Tree – element addition struct node* add(struct node* node, type elem) { if (node == NULL) { return (NewNode(elem)); } else { if (elem data) node->left = add (node->left, elem); else node->right = add (node->right, elem); return (node); } } If the tree is empty, return the new node (write it for exercise!) Else, descend recursively along the tree, to the left or right Return the unchanged pointer to the node What if the element is already stored? 19 / 31

Algorithms and data structures, FER Function to create a new node struct node* NewNode(int elem) { struct node* new = (node *) malloc(sizeof(struct node)); new->data = elem; new->left = NULL; new->right = NULL; return(new); } 20 / 31

Algorithms and data structures, FER Searching the tree int search (struct node* node, int looked_for) { if (node == NULL) { return 0; } else { if (looked_for == node->data) return 1; else { if (looked_for data) return (serch(node->left, looked_for)); else return (search(node->right, looked_for)); } } } Basic case – empty tree, the searched value not found, return 0 Return1 if found Else, descend along the corresponding subtree 21 / 31

Algorithms and data structures, FER Tree traversal n There are 3 standard ways of tree traversal, ensuring that every node has been visited inorder : left subtree → root → right subtree inorder : left subtree → root → right subtree preorder: root → left subtree → right subtree preorder: root → left subtree → right subtree postorder: left subtree → right subtree → root postorder: left subtree → right subtree → root n These are recursive procedures reaching the tree leaves; then the returns from recursion present progressing towards the tree root n An example for inorder from right to left: right subtree → root → left subtree right subtree → root → left subtree n Retrieval of data from the tree with calculations  SortiranoStablo (SortedTree)  ProsjekUStablu (AverageInTree) 22 / 31

Algorithms and data structures, FER Tree – leaf deletion n The simplest case of deletion is deleting a leaf, e.g Delete Release 23 / 31

Algorithms and data structures, FER Tree – deletion of a node with single child n Deleting a node with single child is also simple, e.g Delete Release 24 / 31

Algorithms and data structures, FER n More complex is deletion of a node with two children, e.g Delete Release 5  BrisanjeCvoraStabla (DeletionOfNodeInTree) / 31 Tree – deletion of a node with two children

Algorithms and data structures, FER Exercises n Write the programs to: a. print out the number of nodes in a tree b. print the tree’s depth c. print the values of the smallest and of the largest integer stored in the nodes of a tree d. construct and print out a mirror copy of a given tree e. for two given trees check whether they are identical or not 26 / 31

Algorithms and data structures, FER Exercises In a formatted sequential file students on disk there are records with the following contents: In a formatted sequential file students on disk there are records with the following contents: – ID8 digits – Family name and name40+1 characters – Grades for 10 courses 10*1 digits Write a program to create a new unformatted direct access file index. To enable quick retrieval according to the ID, file records are stored as an ordered binary tree. Write a program to create a new unformatted direct access file index. To enable quick retrieval according to the ID, file records are stored as an ordered binary tree. For a given ID, the ordinal number, and the new grade value write a program that keeps updating the grade as long as the entered ID is greater than zero. For a given ID, the ordinal number, and the new grade value write a program that keeps updating the grade as long as the entered ID is greater than zero. 27 / 31

Algorithms and data structures, FER Exercises n Write a function to print out the elements of a memory resident already existent sorted binary tree with contents in nodes: Article price (integer) Article price (integer) Article name (15+1 characters) Article name (15+1 characters) The tree is sorted according to the article price; left node cheaper, right node more expensive. Input argument is the pointer to the root of the tree. Print out should be ordered from the cheapest to the most expensive article. 28 / 31

Algorithms and data structures, FER Exercises n The sequence of data is stored into a binary tree: 12, 15, 5, 3, 7, 2, 18, 11 a) Draw the sorted binary tree (left smaller, right bigger), if the tree was filled in in the sequence the data are listed b) Reorder the input data to cause a worst case c) Sketch the binary tree for the best case d) What is the a priori execution time for retrieval of a node in case b) e) What is the a priori execution time for retrieval of a node in case c) 29 / 31

Algorithms and data structures, FER Exercises n The codes of length 10+1 characters are stored in a memory resident binary tree. Write a function to check the presence of a given code. Input arguments are the pointer to the tree root and a given code. Output is 0 if the code is not present, and 1 if it is. A node contains the code and pointers to the left and the right child. ID numbers (integer and key) and the persons’ weights (float) are stored in a memory resident sorted binary tree (left smaller, right bigger). Write a function to calculate the total weights of the recorded persons. The function prototype is: ID numbers (integer and key) and the persons’ weights (float) are stored in a memory resident sorted binary tree (left smaller, right bigger). Write a function to calculate the total weights of the recorded persons. The function prototype is: float weight(struct node* root); 30 / 31

Algorithms and data structures, FER Exercises n In a memory resident binary tree, there are stored persons’ IDs (integer) and weights (float). Write a function to calculate the average weight of the recorded persons, the maximum weight and the number of recorded persons. The function prototype is: float average(struct node *root, float *weight, int *number, float *maxweight); n In a memory resident binary tree, there are stored the codes (integer) and the names of courses (15+1 characters). The names of the courses should be printed out so that the tree structure is visible. Level of a node should correspond to the distance from the left margin. The function prototype is: void write (node *root, int level); 31 / 31