TREE DATA STRUCTURE Data Structure 21-Sep-18 Tree

Slides:



Advertisements
Similar presentations
Trees Types and Operations
Advertisements

1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
Trees, Binary Trees, and Binary Search Trees COMP171.
Lec 15 April 9 Topics: l binary Trees l expression trees Binary Search Trees (Chapter 5 of text)
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
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 ),
DATA STRUCTURES AND ALGORITHMS Lecture Notes 5 Prepared by İnanç TAHRALI.
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
Data Structures and Algorithm Analysis Trees Lecturer: Jing Liu Homepage:
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,
Lec 15 Oct 18 Binary Search Trees (Chapter 5 of text)
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use at Midwestern State University Chapter.
Data Structures – Week #5 Trees (Ağaçlar). December 4, 2015Borahan Tümer, Ph.D.2 Trees (Ağaçlar) Toros GöknarıAvrupa Göknarı.
CE 221 Data Structures and Algorithms Chapter 4: Trees (Binary) Text: Read Weiss, §4.1 – 4.2 1Izmir University of Economics.
Review 1 Queue Operations on Queues A Dequeue Operation An Enqueue Operation Array Implementation Link list Implementation Examples.
Tree Traversals, TreeSort 20 February Expression Tree Leaves are operands Interior nodes are operators A binary tree to represent (A - B) + C.
Chapter 4: Trees Part I: General Tree Concepts Mark Allen Weiss: Data Structures and Algorithm Analysis in Java.
Introduction to Trees IT12112 Lecture 05 Introduction Tree is one of the most important non-linear data structures in computing. It allows us to implement.
CISC 235 Topic 3 General Trees, Binary Trees, Binary Search Trees.
Binary Tree. Some Terminologies Short review on binary tree Tree traversals Binary Search Tree (BST)‏ Questions.
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.
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.
1 Trees General Trees  Nonrecursive definition: a tree consists of a set of nodes and a set of directed edges that connect pairs of nodes.
TREES General trees Binary trees Binary search trees AVL trees Balanced and Threaded trees.
Trees CSIT 402 Data Structures II 1. 2 Why Do We Need Trees? Lists, Stacks, and Queues are linear relationships Information often contains hierarchical.
DS.T.1 Trees Chapter 4 Overview Tree Concepts Traversals Binary Trees Binary Search Trees AVL Trees Splay Trees B-Trees.
CSE 373 Data Structures Lecture 7
Trees Saurav Karmakar
CS 201 Data Structures and Algorithms
CC 215 Data Structures Trees
COMP 53 – Week Fourteen Trees.
BCA-II Data Structure Using C
Tree.
Week 6 - Wednesday CS221.
CS 201 Data Structures and Algorithms
Trees Another Abstract Data Type (ADT)
Lecture 22 Binary Search Trees Chapter 10 of textbook
CMSC 341 Introduction to Trees.
CSE 373 Data Structures Lecture 7
abstract containers sequence/linear (1 to 1) hierarchical (1 to many)
Binary Search Trees Why this is a useful data structure. Terminology
Binary Trees, Binary Search Trees
Chapter 22 : Binary Trees, AVL Trees, and Priority Queues
Chapter 7 TREES.
TREES General trees Binary trees Binary search trees AVL trees
Introduction to Trees IT12112 Lecture 05.
Trees, Binary Trees, and Binary Search Trees
CS212: Data Structures and Algorithms
Lec 12 March 9, 11 Mid-term # 1 (March 21?)
AVL Trees: AVL Trees: Balanced binary search tree
Trees CSE 373 Data Structures.
Trees Another Abstract Data Type (ADT)
Trees Another Abstract Data Type (ADT)
Data Structures – Week #5
CMSC 202 Trees.
CE 221 Data Structures and Algorithms
Data Structures and Algorithm Analysis Trees
Binary Trees, Binary Search Trees
CE 221 Data Structures and Algorithms
Trees.
Lecture 10 Oct 1, 2012 Complete BST deletion Height-balanced BST
Trees BST, AVL, SPLAY TREES
Trees CSE 373 Data Structures.
Binary Trees, Binary Search Trees
Tree (new ADT) Terminology: A tree is a collection of elements (nodes)
Presentation transcript:

TREE DATA STRUCTURE Data Structure 21-Sep-18 Tree Dr.P.Deepalakshmi, CSE/KARE

Tree - Data Structure A tree is a collection of nodes. The collection can be empty, which is sometimes denoted as A. Otherwise, a tree consists of a distinguished node r, called the root, and zero or more (sub)trees T1 , T2 , . . . , Tk , each of whose roots are connected by a directed edge to r. The root of each subtree is said to be a child of r, and r is the parent of each subtree root. Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Tree - Data Structure So, a tree is a collection of n nodes, one of which is the root, and n - 1 edges. That is there are n - 1 edges which follows from the fact that each edge connects some node to its parent, and every node except the root has one parent Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Tree - Terms Leaf - Nodes with no children are known as leaves Siblings - Nodes with the same parent are siblings Path - A path from node n1 to nk is defined as a sequence of nodes n1 , n2, .. . , nk such that ni is the parent of ni+1 for 1<= i < k. Length – length of a path is the number of edges on the path. Depth - length of the unique path from the root to ni ; root is at depth 0. Height – Height of a node ni is the longest path from ni to a leaf; So, all leaves are at height 0. Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Tree - Terms The height of a tree is equal to the height of the root. The depth of a tree is equal to the depth of the deepest leaf which is always equal to the height of the tree. If there is a path from n1 to n2 , then n1 is an ancestor of n2 and n2 is a descendant of n1. Tree Node Structure typedef struct tree_node *tree_ptr; struct tree_node { element_type element; tree_ptr first_child; tree_ptr next_sibling; }; Simple Structure struct treenode { int element; struct treenode *first_child; struct treenode *next_sibling; }; Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Tree - Implementation A tree Implementation 21-Sep-18 Tree Dr.P.Deepalakshmi, CSE/KARE

Tree - Applications to implement the file system / directory structure in many common operating systems, including UNIX, VAX/VMS, and DOS. to evaluate arithmetic expressions to support searching operations in O(log n) average time Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Tree Applications – File Systems 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

List a directory in a hierarchical file system void list_directory ( Directory_or_file D ) { list_dir ( D, 0 ); } void list_dir ( Directory_or_file D, unsigned int depth ) /*1*/ if ( D is a legitimate entry) /*2*/ print_name ( depth, D ); /*3*/ if( D is a directory ) /*4*/ for each child, c, of D /*5*/ list_dir( c, depth+1 ); Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Unix directory with file sizes Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

To calculate the size of a directory unsigned int size_directory( Directory_or_file D ) { unsigned int total_size; /*1*/ total_size = 0; /*2*/ if( D is a legitimate entry) /*3*/ total_size = file_size( D ); /*4*/ if( D is a directory ) /*5*/ for each child, c, of D /*6*/ total_size += size_directory( c ); } /*7*/ return( total_size ); Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Tree Traversals Traversal refers to the process of visiting (checking and/or updating) each node in a tree data structure, exactly once. Taversals are classified by the order in which the nodes are visited as follows. Preorder Traversal Postorder Traversal Ignored Traversal Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Tree Traversals Preorder : A B C D H E I J P Q F K L M G N Preorder Traversal Display the data part of the root (or current node). Traverse First subtree using Preorder traversal Traverse the Second subtree using preorder traversal Continue this till last subtree using preorder traversal Preorder : A B C D H E I J P Q F K L M G N Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Tree Traversals Postorder : B C H D I P Q J E K L M F N G A Postorder Traversal Traverse First subtree using Postorder traversal Traverse the Second subtree using postorder traversal Continue this till last subtree using postorder traversal Display the data part of the root (or current node). Postorder : B C H D I P Q J E K L M F N G A Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Trees BINARY TREE Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Worst-case binary tree Binary trees A binary tree is a tree in which no node can have more than two children. A node can have a left and a right child, a left child only, a right child only, or no children The tree made up of a left child (of a node x) and all its descendents is called the left subtree of x Similar with Right Subtree Simple Structure struct treenode { int element; struct treenode *left_child; struct treenode *right_child; }; Worst-case binary tree (skew Tree) Generic binary tree Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Binary trees - Traversals In Preorder, the root is visited before (pre) the subtrees traversals In Inorder, the root is visited in-between left and right subtree traversal In Postorder, the root is visited after the subtrees traversals Preorder Traversal: Visit the root Traverse left subtree Traverse right subtree Inorder Traversal: Traverse left subtree Visit the root Traverse right subtree Postorder Traversal: Traverse left subtree Traverse right subtree Visit the root 21-Sep-18 Tree Dr.P.Deepalakshmi, CSE/KARE

Binary trees - Traversals Preorder a b c e k h j m d f i g Inorder c b h k j e m a f d h i Postorder c h j k m e b f g i d a Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Expression Trees Expression tree is a binary tree in which leaves represents operands, such as variables and constant names and other node contains operators. The inorder, postorder, preorder traversal of expression tree will produce infix, postfix and prefix notation for the expression under consideration. Expression tree for (a + b * c) + ((d * e + f ) * g) Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Constructing Expression Trees From Postfix Read give expression one symbol at a time. If the symbol is an operand, we create a one-node tree and push a pointer to it onto a stack. (stack contains tree nodes) If the symbol is an operator, pop pointers to two trees T1 and T2 from the stack (T1 is popped first) Now form a new tree whose root is the operator and whose left and right children point to T2 and T1 respectively. Push a pointer to this new tree onto the stack. Repeat this till the last symbol and final the constructed expression tree will alone be remaining in the stack. Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Constructing Expression Trees From Postfix Steps : Input a b + c d e + * * The first two symbols are operands, so we create one- node trees and push pointers to them onto a stack. Next, a '+' is read, so two pointers to trees are popped. (T1 – b, T2 – a) A new tree is formed with + as the root and T2 as left child and T1 as right child, and a pointer to it is pushed onto the stack Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Constructing Expression Trees From Postfix Steps : a b + c d e + * * Next, c, d, and e are read, and for each a one-node tree is created and a pointer to the corresponding tree is pushed onto the stack. After + is read, the tree will be Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Constructing Expression Trees From Postfix Steps : a b + c d e + * * Continuing this, '*' is read, so we pop two tree pointers and form a new tree with a '*' as root. Finally, the last symbol is read, two trees are merged, and a pointer to the final tree is left on the stack. Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Constructing Expression Trees From Postfix Steps : a b + c d e + * * Continuing this, '*' is read, so we pop two tree pointers and form a new tree with a '*' as root. Finally, the last symbol is read, two trees are merged, and a pointer to the final tree is left on the stack. Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

BINARY SERACH TREE Data Structure 21-Sep-18 Tree Dr.P.Deepalakshmi, CSE/KARE

Binary Search Tree In a binary search tree , for every node, X, in the tree, the values of all the keys in the left subtree are smaller than the key value in X, and the values of all the keys in the right subtree are larger than the key value in X. In following tree, identify BST. Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Binary Search Tree - Operations Supports following dynamic set operations Make the tree Empty Find an Element Find a Minimum element in tree Find a Maximum element in tree Insert an Element Delete an Element Can be used to build Dictionaries. Priority Queues. Basic operations take time proportional to the height of the tree – O(h). http://btv.melezinek.cz/binary-search-tree.html Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Binary Search Tree - Operations Node Representation struct treenode { int element; struct treenode *left; struct treenode *right; }; Use create node procedure to allocate memeory and make left and right to point to NULL. Make the tree empty struct treenode* make_null ( void ) // call Tree1 = make_null(); return NULL; } Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Binary Search Tree – Find Operation struct treenode* find( int x, struct treenode* T ) { if( T == NULL ) return NULL; if( x < T->element ) return( find( x, T->left ) ); else if( x > T->element ) return( find( x, T->right ) ); else return T; } If T is NULL, then we can just return NULL. Otherwise, if the key stored at T is x, we can return T. Otherwise, we make a recursive call on a subtree of T, either left or right, depending on the relationship of x to the key stored in T. Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Binary Search Tree – FindMin Operation To perform a find_min, start at the root and go left as long as there is a left child. The stopping point is the smallest element. FindMin struct treenode* find_min( struct treenode* T ) { if( T == NULL ) return NULL; else if( T->left == NULL ) return( T ); else return( find_min ( T->left ) ); } Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Binary Search Tree – FindMax Operation To perform a find_max, start at the root and go right as long as there is a right child. The stopping point is the largest element. FindMin struct treenode* find_max( struct treenode* T ) { if( T == NULL ) return NULL; else if( T->right == NULL ) return( T ); else return( find_max ( T->right ) ); } Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Binary Search Tree - Operations FindMin – Non Recursive Version struct treenode* find_min( struct treenode* T ) { struct treenode *Temp = T while(Temp) if( Temp == NULL ) return NULL; else if( Temp->left == NULL ) return( Temp ); else Temp = Temp->left; } FindMax – Non Recursive Version struct treenode* find_max( struct treenode* T ) { struct treenode *Temp = T while(Temp) if( Temp == NULL ) return NULL; else if( Temp->right == NULL ) return( Temp ); else Temp = Temp->right; } Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Binary Search Tree – Insert Operation Start from the root node if one such exists. Otherwise make this as root node If the node to insert is less than the root, go to left child otherwise go to the right child of the root. Continue this process (each node is a root for some sub tree) until a null pointer or leaf node is found and can not go any further. If value at current node and new value are equal, no need to insert new value since already it exists in BST. Insert the node as a left child if new value is less than current nodes key value. Otherwise insert the node as a right child since new value is greater than current node. A new node is always inserted as a leaf node. Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Binary Search Tree – Insert Operation struct treenode* insert( int x, struct treenode* T ) { if( T == NULL ) T =createtreenode(); printf("Out of space!!!"); else T->element = x; T->left = T->right = NULL; } else if( x < T->element ) T->left = insert( x, T->left ); else if( x > T->element ) T->right = insert( x, T->right ); return T; Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Binary Search Tree – Deletion Operation In trees, the hardest operation is deletion. If the node is a leaf, it can be deleted immediately If the node has one child, the node can be deleted after its parent adjusts a pointer to bypass the node Deletion of a node (4) with one child, before and after Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Binary Search Tree – Deletion Operation To delete a node with two children, replace the key of this node with the smallest key of the right subtree and recursively delete that node. Deletion of a node (2) with two children, before and after Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Binary Search Tree – Deletion Operation struct treenode* deletion( int x, struct treenode* T ) { struct treenode *tmp_cell, *child; if( T == NULL ) printf("Element not found"); else if( x < T->element ) /* Go left */ T->left = deletion( x, T->left ); else if( x > T->element ) /* Go right */ T->right = deletion( x, T->right ); else if( T->left && T->right ) /* 2 child - replace with smallest in right subtree */ tmp_cell = find_min( T->right ); T->element = tmp_cell->element; T->right = deletion( T->element, T->right ); } Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Binary Search Tree – Deletion Operation else /* One child */ { tmp_cell = T; if( T->left == NULL ) /* Only a right child */ child = T->right; if( T->right == NULL ) /* Only a left child */ child = T->left; free( tmp_cell ); return child; } return T; Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

Binary Search Tree – Problem Do following with appropriate steps Perform Preorder, Inorder, Post order traversal Insert 5 Insert 9 Insert 11 Find 14 Find Min Find Max Delete 3 Delete 14 Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

AVL Trees Data Structure - Trees 21-Sep-18 Tree Dr.P.Deepalakshmi, CSE/KARE

Data Structure - Trees 3 18 8 5 13 20 22 Number of operations to find 22 in both trees? Which is faster? Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

AVL Trees An AVL (Adelson-Velskii and Landis) tree is identical to a binary search tree, except that for every node in the tree, the height of the left and right subtrees can differ by at most 1. (The height of an empty tree is defined to be -1 & height of a leaf node is 0.) This balance condition ensures that the depth of the tree is O(log n). In following trees, identify which is AVL tree? Because At 6, height of Left subtree is 2 and height of right subtree is 0 and the difference is 2. So, right BST is not an AVL tree. . (Left is only AVL tree) Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

AVL Trees Smallest AVL tree of height 9 All the AVL tree operations can be performed in O(log n) time except insertion. Because during an insertion, we need to update all the balancing information for the nodes on the path back to the root. This can always be done with a simple modification to the tree, known as a single rotation and double rotation. Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

AVL Trees – Single Rotation Start at the node inserted and travel up the tree. update the balance information at every node on the path. If we get to the root without having found any badly balanced nodes, no need for any rotation. Otherwise, a rotation at the first bad node found is required to adjust its balance. We can stop here and need not to continue going to the root. The conversion of one of the above trees to the other is known as a rotation. Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

AVL Trees – Single Rotation Type 1 : Right Rotation (Left subtree has more height) When new value is inserted in the subtree A, The AVL-property is violated at x since height of left(x) is h+2 but height of right(x) is h. So rotate with left child y. Make y as a parent, x as its right child and y’s right child as left child of x. Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

AVL Trees – Single Rotation Type 2 : Left Rotation(Right subtree has more height) When new value is inserted in the subtree A, The AVL-property is violated at x since height of right(x) is h+2 but height of left(x) is h. So rotate with right child y. Make y as a parent, x as its left child and y’s left child as right child of x. Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

AVL Trees – Single Rotation A rotation involves only a few pointer changes and alters the structure of the tree while preserving the search tree property. AVL property is destroyed by insertion of 6.5, and fixed by a rotation Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

AVL Trees – Single Rotation Insert elements 1 to 7 in a BST and maintain AVL tree properties Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

AVL Trees – Single Rotation Insert elements 1 to 7 in a BST and maintain AVL tree properties Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

AVL Trees – Single Rotation In some cases single rotation may not balance the height properly. inserting 14 causes a height imbalance at node 7 and so a rotate with right child is done. This is caused mainly because of the middle element 14. So double rotation is required. Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

AVL Trees – Double Rotation Double rotation involves 4 subtrees (Left-right) double rotation (Right-left) double rotation Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

AVL Trees – Double Rotation Insert 15, 14 in previous tree ( 1 to 7) Here the double rotation is a right-left double rotation involving 7, 15, 14. k1 is 15, k2 is 14 and k3 is 7. Make k2 as parent node and k3 as left child and k1 as its right child. Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

AVL Trees – Double Rotation Insert 13. Imbalance occurs at 6 involving a right-left. So k1 is 14, k2 is 7 and k3 is 6. Take k2(7) as parent and make k3 (6) as left child and k1(14) as right child. Now k2’s(7) right goes to k1’s(14) left Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

AVL Trees – Double Rotation Insert 12 Imbalance occurs at 4 with right-right. So single left rotation is enough. Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

AVL Trees – Double Rotation Insert 11 Imbalance occrist at 13 with left-left. So, single right rotation is enough. Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE

AVL Trees – Double Rotation Final diagram after inserting 9, 8. Draw intermediate diagrams. Not try to insert 8.5 https://www.cs.usfca.edu/~galles/visualization/AVLtree.html Tree 21-Sep-18 Dr.P.Deepalakshmi, CSE/KARE