DATA STRUCTURES AND ALGORITHMS Lecture Notes 5 Prepared by İnanç TAHRALI.

Slides:



Advertisements
Similar presentations
DATA STRUCTURES AND ALGORITHMS Lecture Notes 9 Prepared by İnanç TAHRALI.
Advertisements

Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
Computer Science 2 Data Structures and Algorithms V section 2 Introduction to Trees Professor: Evan Korth New York University.
Trees, Binary Trees, and Binary Search Trees COMP171.
Trees, Binary Trees, and Binary Search Trees. 2 Trees * Linear access time of linked lists is prohibitive n Does there exist any simple data structure.
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.
1 BST Trees A binary search tree is a binary tree in which every node satisfies the following: the key of every node in the left subtree is.
CS 146: Data Structures and Algorithms June 18 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Binary Search Trees. BST Properties Have all properties of binary tree Items in left subtree are smaller than items in any node Items in right subtree.
1 Chapter 18 Trees Objective To learn general trees and recursion binary trees and recursion tree traversal.
Trees Chapter 8. 2 Tree Terminology A tree consists of a collection of elements or nodes, organized hierarchically. The node at the top of a tree is called.
Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.
Tree. Basic characteristic Top node = root Left and right subtree Node 1 is a parent of node 2,5,6. –Node 2 is a parent of node.
Trees Basic concepts of trees Implementation of trees Traversals of trees Binary trees Binary search trees AVL trees B-trees.
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
CMSC 341 Introduction to Trees. 8/3/2007 UMBC CMSC 341 TreeIntro 2 Tree ADT Tree definition  A tree is a set of nodes which may be empty  If not empty,
BINARY SEARCH TREE. Binary Trees A binary tree is a tree in which no node can have more than two children. In this case we can keep direct links to the.
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.
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,
CS 202, Spring 2003 Fundamental Structures of Computer Science II Bilkent University1 Trees CS 202 – Fundamental Structures of Computer Science II Bilkent.
CE 221 Data Structures and Algorithms Chapter 4: Trees (Binary) Text: Read Weiss, §4.1 – 4.2 1Izmir University of Economics.
CMSC 341 Introduction to Trees. 2/21/20062 Tree ADT Tree definition –A tree is a set of nodes which may be empty –If not empty, then there is a distinguished.
CISC 235 Topic 3 General Trees, Binary Trees, Binary Search Trees.
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.
CSCS-200 Data Structure and Algorithms Lecture
AL-HUSEEN BIN TALAL UNIVERSITY College of Engineering Department of Computer Engineering Algorithms and Data Structures Binary Tree Course No.:
CMSC 341 Binary Search Trees. 8/3/2007 UMBC CMSC 341 BST 2 Binary Search Tree A Binary Search Tree is a Binary Tree in which, at every node v, the values.
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.
Definitions Read Weiss, 4.1 – 4.2 Implementation Nodes and Links One Arrays Three Arrays Traversals Preorder, Inorder, Postorder K-ary Trees Converting.
1 CMSC 341 Introduction to Trees Textbook sections:
1 Trees. 2 Trees Trees. Binary Trees Tree Traversal.
1 Trees 3: The Binary Search Tree Reading: Sections 4.3 and 4.6.
DS.T.1 Trees Chapter 4 Overview Tree Concepts Traversals Binary Trees Binary Search Trees AVL Trees Splay Trees B-Trees.
1 Trees. 2 Outline Preliminaries –What is Tree? –Implementation of Trees using C++ –Tree traversals and applications Binary Trees Binary Search Trees.
CSE 373 Data Structures Lecture 7
Trees Saurav Karmakar
CS 201 Data Structures and Algorithms
CC 215 Data Structures Trees
CMSC 341 Introduction to Trees 8/3/2007 CMSC 341 Tree Intro.
CMSC 341 Introduction to Trees.
CSE 373 Data Structures Lecture 7
TREE DATA STRUCTURE Data Structure 21-Sep-18 Tree
Binary Trees, Binary Search Trees
CMSC 341 Lecture 10 Binary Search Trees
Trees 3: The Binary Search Tree
Trees, Binary Trees, and Binary Search Trees
Trees.
CMSC 341 Introduction to Trees.
CMSC 341 Introduction to Trees.
Trees CSE 373 Data Structures.
Trees.
CMSC 341 Binary Search Trees.
Trees Basic concepts of trees Implementation of trees
CE 221 Data Structures and Algorithms
Data Structures and Algorithm Analysis Trees
Binary Trees, Binary Search Trees
CE 221 Data Structures and Algorithms
CMSC 341 Introduction to Trees CMSC 341 Tree Intro.
CMSC 341 Binary Search Trees.
Tree.
Trees BST, AVL, SPLAY TREES
Trees CSE 373 Data Structures.
Trees CSE 373 Data Structures.
CMSC 341 Binary Search Trees 2/21/2006.
Binary Trees, Binary Search Trees
Data Structures Using C++ 2E
Presentation transcript:

DATA STRUCTURES AND ALGORITHMS Lecture Notes 5 Prepared by İnanç TAHRALI

2 ROAD MAP TREES Definitions and Terminology Implementation of Trees Tree Traversals Binary Trees The Search Tree ADT-Binary Search Trees AVL Trees

3 TREES: Definition Recursive Definition : Tree is a collection of nodes A tree can be empty A tree contains zero or more subtrees T 1, T 2,… T k connected to a root node by edges

4 TREES: Terminology Family Tree Terminology child  F is child of A parent  A is the parent of F each node is connected to a parent except the root sibling  nodes with same parents (K, L, M) leaf  nodes with no children (P, Q) Ancestor / Descendant

5 Path : a sequence of nodes n 1, n 2, … n k, where n i is the parent of n i +11≤i<k Lenght : number of edges on the path (k-1) Depth : depth of n i is the lenght of unique path from the root to n i –depth of root is 0 –depth of a tree = depth of the deepest leaf Height : height of n i is the lenght of the longest path from n i to a leaf –height of a leaf is 0 –height of a tree = height of the root = depth of the tree

6 Implementation of Trees 1. Each node contains a pointer to each of its children number of children would be large 2. Each node contains an array of pointers to its children number of children may vary greatly (waste of space)

7 Implementation of Trees 3. Each node contains a linked list of the children struct TreeNode { Object element; TreeNode *firstChild; TreeNode *nextSibling; }

8 ROAD MAP TREES Implementation of Trees Tree Traversals Binary Trees The Search Tree ADT-Binary Search Trees AVL Trees

9 Tree Traversals One of the most popular applications of trees is the directory structure of O/S

10 Preorder Tree Traversals work on the node first before its children ! void FileSystem::listAll(int depth = 0)const{ printName(depth); if (isDirectory()) for each file c in this directory (for each child) c.listAll(depth+1); } Pseudocode to list a directory in a hierarchical file system

11 Postorder Tree Traversals work on the node after its children ! Pseudocode to calculate the size of a directory int FileSystem::size () const{ int totalSize = sizeOfThisFile (); if (isDirectory()) for each file c in this directory totalSize += c.size(); return totalsize; }

12 ROAD MAP TREES Implementation of Trees Tree Traversals Binary Trees The Search Tree ADT-Binary Search Trees AVL Trees

13 Binary Trees Definition : A tree in which nodes have at most two children Generic Binary Tree

14 Binary Trees Binary TreeWorst case binary tree

15 Implementation of Binary Trees keep a pointer to left child and right child struct BinaryNode { Object element; BinaryNode *left; BinaryNode *right; }

16 Example: Expression Trees Leaves contain operands Internal nodes contain operators Inorder traversal => infix expression Preorder traversal => prefix expression Postorder traversal => postfix expression

17 Expression Trees Entire tree represents (a+(b*c))+(((d*e)+f)*g) Left subtree represents a+(b*c) Right subtree represents ((d*e)+f)*g

18 Constructing an Expression Tree Algorithm to convert a postfix expresion into an expression tree read the expression one symbol at a time. if the symbol is operand create a one-node tree push the tree onto a stack if the symbol is operator pop two trees T 1 and T 2 from the stack form a new tree whose root is the operator and whose left and right subtrees are T 2 and T 1 respectively This new tree is pushed onto the stack

19 Example: input is ab+cde+** First two symbols are operands create one-node trees push pointers to them onto a stack Next + is read pointers to trees are poped a new tree is formed a pointer to it is pushed onto the stack

20 Example: input is ab+cde+** c, d, e are read for each a one-node tree is created A pointer to the corresponding tree is pushed onto the stack.

21 Example: input is ab+cde+** + is read two trees are merged

22 Example: input is ab+cde+** * is read pop two tree pointers and form a new tree with a * as root

23 Example: input is ab+cde+** Last symbol is read two trees are merged a pointer to the final tree is left on the stack

24 ROAD MAP TREES Implementation of Trees Tree Traversals Binary Trees The Search Tree ADT-Binary SearchTrees AVL Trees

25 Binary Search Trees Each node in tree stores an item items are integers and distinct deal with dublicates later Properties A binary tree for each node x values at left subtree are smaller values at right subtree are larger than the value of x

26 Binary Search Trees Which one of the trees below is binary search tree ?

27 Binary Search Trees template class BinarySearchTree template class BinaryNode { Comparable element; BinaryNode *left; BinaryNode *right; BinaryNode( const Comparable & theElement, BinaryNode *lt, BinaryNode *rt ) : element( theElement ), left( lt ), right( rt ) { } friend class BinarySearchTree };

28 template class BinarySearchTree { public: explicit BinarySearchTree( const Comparable & notFound); BinarySearchTree( const BinarySearchTree & rhs ); ~BinarySearchTree( ); const Comparable & findMin( ) const; const Comparable & findMax( ) const; const Comparable & find (const Comparable & x) const; bool isEmpty( ) const; void printTree( ) const; void makeEmpty( ); void insert( const Comparable & x ); void remove( const Comparable & x ); const BinarySearchTree & operator= ( const BinarySearchTree & rhs ); private: BinaryNode *root; const Comparable ITEM_NOT_FOUND;

29 int main( ) { const int ITEM_NOT_FOUND = -9999; BinarySearchTree t( ITEM_NOT_FOUND ); int NUMS = 4000; const int GAP = 37; int i; for( i = GAP; i != 0; i = ( i + GAP ) % NUMS ) t.insert( i ); for( i = 1; i < NUMS; i+= 2 ) t.remove( i ); if( NUMS < 40 ) t.printTree( ); if( t.findMin( ) != 2 || t.findMax( ) != NUMS - 2 ) cout << "FindMin or FindMax error!" << endl; for( i = 2; i < NUMS; i+=2 ) if( t.find( i ) != i ) cout << "Find error1!" << endl; for( i = 1; i < NUMS; i+=2 ) { if( t.find( i ) != ITEM_NOT_FOUND ) cout << "Find error2!"<< endl;} BinarySearchTree t2( ITEM_NOT_FOUND ); t2 = t; for( i = 2; i < NUMS; i+=2 ) if( t2.find( i ) != i ) cout << "Find error1!" << endl; return 0; }

30 template class BinarySearchTree { public: explicit BinarySearchTree( const Comparable & notFound); BinarySearchTree( const BinarySearchTree & rhs ); ~BinarySearchTree( ); const Comparable & findMin( ) const; const Comparable & findMax( ) const; const Comparable & find (const Comparable & x) const; bool isEmpty( ) const; void printTree( ) const; void makeEmpty( ); void insert( const Comparable & x ); void remove( const Comparable & x ); const BinarySearchTree & operator= ( const BinarySearchTree & rhs ); private: BinaryNode *root; const Comparable ITEM_NOT_FOUND;

31 private: const Comparable & elementAt ( BinaryNode *t) const; void insert ( const Comparable & x, BinaryNode * & t ) const; void remove ( const Comparable & x, BinaryNode * & t ) const; BinaryNode * findMin ( BinaryNode *t ) const; BinaryNode * findMax ( BinaryNode *t ) const; BinaryNode * find ( const Comparable & x, BinaryNode *t ) const; void makeEmpty ( BinaryNode * & t ) const; void printTree ( BinaryNode *t ) const; BinaryNode * clone ( BinaryNode ) *t ) const; };

32 find /* Find item x in the tree - Return the matching item or ITEM_NOT_FOUND if not found. */ template const Comparable & BinarySearchTree :: find( const Comparable & x ) const { return elementAt( find( x, root ) ); } template const Comparable & BinarySearchTree :: elementAt( BinaryNode *t ) const { if( t == NULL ) return ITEM_NOT_FOUND; else return t->element; }

33 find

34 find /* Find item x in the tree - Return the node containinig the matching item or NULL if not found. */ template BinaryNode * BinarySearchTree :: find ( const Comparable & x, BinaryNode *t ) const; { if (t==NULL) return NULL; else if (x element) return find( x, t->left ); else if (t->element < x) return find( x, t->right ); else retun t; }

35 Recursive implementation of findMin /* Internal method to find the smallest item in a subtree t. */ template BinaryNode * BinarySearchTree ::findMin( BinaryNode *t ) const { if( t == NULL ) return NULL; if( t->left == NULL ) return t; return findMin( t->left ); }

36 Non-recursive implementation of findMax template BinaryNode * BinarySearchTree ::findMax( BinaryNode *t ) const { if( t != NULL ) while( t->right != NULL ) t = t->right; return t; }

37 insert into a binary search tree

38 insert into a binary search tree template void BinarySearchTree :: insert( const Comparable & x, BinaryNode * & t ) const { if( t == NULL ) t = new BinaryNode ( x, NULL, NULL ); else if( x element ) insert( x, t->left ); else if( t->element < x ) insert( x, t->right ); else ; // Duplicate; do nothing }

39 Remove

40 Remove template void BinarySearchTree :: remove( const Comparable & x, BinaryNode * & t ) const { if( t == NULL ) return; if( x element ) remove( x, t->left ); else if( t->element right ); else if( t->left != NULL && t->right != NULL ) { t->element = findMin( t->right )->element; remove( t->element, t->right ); } else { BinaryNode *oldNode = t; t = ( t->left != NULL ) ? t->left : t->right; delete oldNode; }

41 Destructor and recursive makeEmpty /* Destructor for the tree. */ template BinarySearchTree ::~BinarySearchTree( ){ makeEmpty( ); } template void BinarySearchTree :: makeEmpty( BinaryNode * & t ) const { if( t != NULL ) { makeEmpty( t->left ); makeEmpty( t->right ); delete t; } t = NULL; }

42 Operator = template const BinarySearchTree & BinarySearchTree :: operator=( const BinarySearchTree & rhs ) { if( this != &rhs ){ makeEmpty( ); root = clone( rhs.root ); } return *this; }

43 Recursive clone member function template BinaryNode * BinarySearchTree ::clone( BinaryNode * t ) const { if( t == NULL ) return NULL; else return new BinaryNode ( t->element, clone( t->left ), clone( t->right ) ); }