Presentation is loading. Please wait.

Presentation is loading. Please wait.

Algorithms and data structures Protected by 14.9.2015.

Similar presentations


Presentation on theme: "Algorithms and data structures Protected by 14.9.2015."— Presentation transcript:

1 Algorithms and data structures Protected by http://creativecommons.org/licenses/by-nc-sa/3.0/hr/ 14.9.2015

2 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 http://creativecommons.org/licenses/by-nc-sa/3.0/ 14.9.2015Algorithms 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

3 14.9.2015 Trees

4 Algorithms and data structures, FER14.9.2015 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

5 Algorithms and data structures, FER14.9.2015 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

6 Algorithms and data structures, FER14.9.2015 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

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

8 Algorithms and data structures, FER14.9.2015 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

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

10 Algorithms and data structures, FER14.9.2015 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

11 Algorithms and data structures, FER14.9.2015 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

12 Algorithms and data structures, FER14.9.2015 Skewed and complete tree Complete tree abdhpcefgijklmno abcde Skewed tree 12 / 31

13 Algorithms and data structures, FER14.9.2015 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 12481635679101112131415 13 / 31

14 Algorithms and data structures, FER14.9.2015 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

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

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

17 Algorithms and data structures, FER14.9.2015 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

18 Algorithms and data structures, FER14.9.2015 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

19 Algorithms and data structures, FER14.9.2015 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

20 Algorithms and data structures, FER14.9.2015 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

21 Algorithms and data structures, FER14.9.2015 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

22 Algorithms and data structures, FER14.9.2015 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

23 Algorithms and data structures, FER14.9.2015 Tree – leaf deletion n The simplest case of deletion is deleting a leaf, e.g. 6. 6 5 3 1 7 4 6 5 3 1 7 4 Delete Release 23 / 31

24 Algorithms and data structures, FER14.9.2015 Tree – deletion of a node with single child n Deleting a node with single child is also simple, e.g. 7 6 5 4 1 7 3 6 5 4 1 7 3 Delete Release 24 / 31

25 Algorithms and data structures, FER14.9.2015 n More complex is deletion of a node with two children, e.g. 5 6 5 3 1 7 4 Delete Release 5  BrisanjeCvoraStabla (DeletionOfNodeInTree) 6 4 1 7 3 25 / 31 Tree – deletion of a node with two children

26 Algorithms and data structures, FER14.9.2015Exercises 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

27 Algorithms and data structures, FER14.9.2015Exercises 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

28 Algorithms and data structures, FER14.9.2015Exercises 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

29 Algorithms and data structures, FER14.9.2015Exercises 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

30 Algorithms and data structures, FER14.9.2015Exercises 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

31 Algorithms and data structures, FER14.9.2015Exercises 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


Download ppt "Algorithms and data structures Protected by 14.9.2015."

Similar presentations


Ads by Google