CS 201 Data Structures and Algorithms Chapter 4: Trees (BST) Text: Read Weiss, §4.3 1Izmir University of Economics.

Slides:



Advertisements
Similar presentations
§2 Binary Trees Note: In a tree, the order of children does not matter. But in a binary tree, left child and right child are different. A B A B andare.
Advertisements

Trees Types and Operations
Binary Search Trees Azhar Maqsood School of Electrical Engineering and Computer Sciences (SEECS-NUST)
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.
AA Trees another alternative to AVL trees. Balanced Binary Search Trees A Binary Search Tree (BST) of N nodes is balanced if height is in O(log N) A balanced.
4.5 AVL Trees  A tree is said to be balanced if for each node, the number of nodes in the left subtree and the number of nodes in the right subtree differ.
1 Chapter 6 Priority Queues (Heaps) General ideas of priority queues (Insert & DeleteMin) Efficient implementation of priority queue Uses of priority queues.
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.
Chapter 12 Trees. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define trees as data structures Define the terms.
TCSS 342 BST v1.01 BST addElement To addElement(), we essentially do a find( ). When we reach a null pointer, we create a new node there. void addElement(Object.
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.
1 Trees 3: The Binary Search Tree Section Binary Search Tree A binary tree B is called a binary search tree iff: –There is an order relation
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 Search Trees - Motivation Assume you would like to store several (key, value) pairs in a data structure that would support the following operations efficiently.
Advanced Algorithms Analysis and Design Lecture 8 (Continue Lecture 7…..) Elementry Data Structures By Engr Huma Ayub Vine.
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.
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
S EARCHING AND T REES COMP1927 Computing 15s1 Sedgewick Chapters 5, 12.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 5 Prepared by İnanç TAHRALI.
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,
Lec 15 Oct 18 Binary Search Trees (Chapter 5 of text)
CE 221 Data Structures and Algorithms Chapter 4: Trees (Binary) Text: Read Weiss, §4.1 – 4.2 1Izmir University of Economics.
CE 221 Data Structures and Algorithms Chapter 6: Priority Queues (Binary Heaps) Text: Read Weiss, §6.1 – 6.3 1Izmir University of Economics.
Binary Search Trees (BSTs) 18 February Binary Search Tree (BST) An important special kind of binary tree is the BST Each node stores some information.
Binary Tree. Some Terminologies Short review on binary tree Tree traversals Binary Search Tree (BST)‏ Questions.
1/14/20161 BST Operations Data Structures Ananda Gunawardena.
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.
Lecture 10COMPSCI.220.FS.T Binary Search Tree BST converts a static binary search into a dynamic binary search allowing to efficiently insert and.
Definitions Read Weiss, 4.1 – 4.2 Implementation Nodes and Links One Arrays Three Arrays Traversals Preorder, Inorder, Postorder K-ary Trees Converting.
1 CSE 326: Data Structures Trees Lecture 6: Friday, Jan 17, 2003.
Trees CSIT 402 Data Structures II 1. 2 Why Do We Need Trees? Lists, Stacks, and Queues are linear relationships Information often contains hierarchical.
1 Trees 3: The Binary Search Tree Reading: Sections 4.3 and 4.6.
CE 221 Data Structures and Algorithms Chapter 4: Trees (AVL Trees) Text: Read Weiss, §4.4 1Izmir University of Economics.
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
CS 201 Data Structures and Algorithms
CC 215 Data Structures Trees
CS 201 Data Structures and Algorithms
Binary Search Trees A binary search tree is a binary tree
Binary Search Tree (BST)
CS 201 Data Structures and Algorithms
CSE 373 Data Structures Lecture 7
TREE DATA STRUCTURE Data Structure 21-Sep-18 Tree
Binary Search Trees Why this is a useful data structure. Terminology
Binary Trees, Binary Search Trees
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Lec 12 March 9, 11 Mid-term # 1 (March 21?)
Trees CSE 373 Data Structures.
CE 221 Data Structures and Algorithms
A Robust Data Structure
CE 221 Data Structures and Algorithms
Data Structures and Algorithm Analysis Trees
Binary Trees, Binary Search Trees
CE 221 Data Structures and Algorithms
CE 221 Data Structures and Algorithms
Binary Search Trees < > = Binary Search Trees
Tree.
Trees CSE 373 Data Structures.
Trees CSE 373 Data Structures.
Binary Trees, Binary Search Trees
Presentation transcript:

CS 201 Data Structures and Algorithms Chapter 4: Trees (BST) Text: Read Weiss, §4.3 1Izmir University of Economics

The Search Tree ADT – Binary Search Trees 2Izmir University of Economics An important application of binary trees is in searching. Let us assume that each node in the tree stores an item. Assume for simplicity that these are distinct integers (deal with duplicates later). The property that makes a binary tree into a binary search tree is that for every node, X, in the tree, the values of all the items in the left subtree are smaller than the item in X, and the values of items in the right subtree are larger than the item in X. The tree on the left is a binary search tree, but the tree on the right is not. The tree on the right has a node with key 7 in the left subtree of a node with key 6 (which happens to be the root).

Izmir University of Economics3 Binary Search Trees - Operations  Descriptions and implementations of the operations that are usually performed on binary search trees (BST) are given.  Note that because of the recursive definition of trees, it is common to write these routines recursively. Because the average depth of a binary search tree is O(log N), we generally do not need to worry about running out of stack space.  Since all the elements can be ordered, we will assume that the operators, and = can be applied to them.

BST – Implementation - I Izmir University of Economics4 typedef int ElementType; struct TreeNode; typedef struct TreeNode *Position; typedef struct TreeNode *SearchTree; struct TreeNode{ ElementType Element; SearchTree Left; SearchTree Right; }; SearchTree MakeEmpty(SearchTree T){ if( T != NULL ){ MakeEmpty( T->Left ); MakeEmpty( T->Right ); free( T ); } return NULL; } Notice that NULL is returned at the end.

Izmir University of Economics5 Find operation generally requires returning a pointer to the node in the Binary Search Tree pointed by T that has value X, or NULL if there is no such node. The structure of the tree makes this simple. If T is NULL, then we can just return. Otherwise, we make a recursive call on either the left or the right subtree of the node pointed by T, depending on the relationship of X to the value stored in the node pointed by T. Otherwise, if the value stored X, we can return T. Position Find(ElementType X, SearchTree T){ if( T == NULL ) return NULL; if( X Element ) return Find( X, T->Left ); else if( X > T->Element ) return Find( X, T->Right ); else return T; } BST – Implementation - II

Izmir University of Economics6 Position FindMin(SearchTree T){ if( T == NULL ) return NULL; else if( T->Left == NULL ) return T; else return FindMin( T->Left ); } Position FindMax(SearchTree T){ if( T != NULL ) while( T->Right != NULL ) T = T->Right; return T; } BST – Implementation - III To perform a FindMin, start at the root and go left as long as there is a left child. The stopping point is the smallest element. The FindMax routine is the same, except that branching is to the right child. Notice that the degenerate case of an empty tree is carefully handled. Also notice that it is safe to change T in FindMax, since we are only working with a copy. Always be extremely careful, however, because a statement such as T->right=T->right->right will make changes.

Izmir University of Economics7 BST – Implementation – Insertion I The insertion routine is conceptually simple. To insert X into tree T, proceed down the tree as you would with a Find. If X is found, do nothing (or "update" something). Otherwise, insert X at the last spot on the path traversed. Duplicates can be handled by keeping an extra field in the node indicating the frequency of occurrence. If the key is only part of a larger record, then all of the records with the same key might be kept in an auxiliary data structure, such as a list or another search tree. → Insert node 5

Izmir University of Economics8 SearchTree Insert(ElementType X, SearchTree T){ if( T == NULL ){ /* Create and return a one-node tree */ T = malloc( sizeof( struct TreeNode ) ); if( T == NULL ) FatalError( "Out of space!!!" ); else { T->Element = X; T->Left = T->Right = NULL; } else if( X Element ) T->Left = Insert( X, T->Left ); else if( X > T->Element ) T->Right = Insert( X, T->Right ); /* Else X is in the tree already; do nothing */ return T; /* Do not forget this line!! */ } BST – Implementation – Insertion II

Izmir University of Economics9 BST – Implementation – Deletion I Once we have found the node to be deleted, we need to consider 3 possibilities. (1)If the node is a leaf, it can be deleted immediately. (2)If the node has one child, the node can be deleted after its parent adjusts a pointer to bypass the node. Notice that the deleted node is now unreferenced and can be disposed of only if a pointer to it has been saved. → Delete node 4

Izmir University of Economics10 BST – Implementation – Deletion II (3)The complicated case deals with a node with two children. The general strategy is to replace the key of this node with the smallest key of the right subtree (easy) and recursively delete that node (which is now empty). Because the smallest node in the right subtree cannot have a left child, the second delete is an easy one. → Delete node 2

11Izmir University of Economics BST – Implementation – Deletion III SearchTree Delete(ElementType X, SearchTree T){ Position TmpCell; /* declare a pointer */ if( T == NULL ) Error( "Element not found" ); else if( X Element ) /* Go left */ T->Left = Delete( X, T->Left ); else if( X > T->Element ) /* Go right */ T->Right = Delete( X, T->Right ); else if( T->Left && T->Right ){ /* Found, it has 2 children */ TmpCell = FindMin( T->Right ); /* smallest in the right */ T->Element = TmpCell->Element; /* Replace with smallest */ T->Right = Delete( T->Element, T->Right ); } else { /* Found, it has one or zero children */ TmpCell = T; T = (T->Left)?T->Left:T->Right;/* Also handles 0 children */ free( TmpCell ); } return T; } Inefficient, since calls highlighted in yellow result in two passes down the tree to find and delete the smallest node in the right subtree.

We can use stacks to convert an expression in standart form (otherwise known as infix) into postfix. Example: operators = {+, *, (, )}, usual precedence rules; a + b * c + (d * e + f) * g Answer = a b c * + d e * f + g * + Izmir University of Economics12 BST – Implementation – Deletion IV SearchTree Delete(ElementType X, SearchTree T){ Position TmpCell, TmpPrevCell; /* declare another pointer */... else if( T->Left && T->Right ){ /* Found, it has 2 children */ TmpCell = T->Right; /* to point to smallest in the right */ TmpPrevCell = T->Right; /* to point to parent of TmpCell */ while (TmpCell->Left != NULL){/* find smallest of right */ TmpPrevCell = TmpCell; TmpCell = TmpCell->Left; } T->Element = TmpCell->Element;/* replace with smallest */ if (TmpCell == TmpPrevCell) /* T->Right is smallest */ T->Right = TmpCell->Right; /* skip over TmpCell */ else /* connect Left of TmpPrevCell to Right of TmpCell */ TmpPrevCell->Left = TmpCell->Right; free (TmpCell); }... } Efficient Version

BST – Implementation – Lazy Deletion If the number of deletions is small, then a popular strategy to use is lazy deletion: When an element is to be deleted, it is left in the tree and merely marked as deleted. This is especially popular if duplicates are present, because then the field that keeps count of the items can be decremented. If the number of real nodes is the same as the number of "deleted" nodes, then the depth of the tree is only expected to go up by a small constant (why?), so there is a very small time penalty associated with lazy deletion. Also, if an item is reinserted, the overhead of allocating a new cell is avoided. Izmir University of Economics13

Average-Case Analysis - I Izmir University of Economics14 All of the operations of BST, except MakeEmpty, take O(d) time where d is the depth of the node containing the accessed key. As a result, they are O (depth of tree). Why? Because in constant time we descend a level in the tree, thus operating on a tree that is now roughly half as large. MakeEmpty take O(N) time. Observation: The average depth over all nodes in a tree is O(log N) assuming all insertion sequences are equally likely. Proof: The sum of the depths of all nodes in a tree is the internal path length. Let’s calculate the average internal path length over all possible insertion sequences.

15Izmir University of Economics Average-Case Analysis - II Let D(N) be the internal path length for some BST T of N nodes. D(1) = 0. D(N) = D(i) + D(N-i-1) + N -1 // Subtree nodes are 1 level deeper All subtree sizes are equally likely for BSTs, since it depends only on the rank of the first element inserted into BST. This does not hold for binary trees though. Let’s, then, average: If the recurrence is solved, D(N) = O(N log N). Thus, the expected depth of any node is O(log N).

Derivation of D(N) - 1 Izmir University of Economics16...(sum the equations side by side).....(divide by N(N+1)).....(subtract (2) from (1))

Izmir University of Economics17 Derivation of D(N) - 2

18Izmir University of Economics Average-Case Analysis - III As an example, the randomly generated 500 node BST has nodes at expected depth 9.98.

Izmir University of Economics19 Average-Case Analysis - IV After a quarter-million random insert/remove pairs, right-heavy tree on the previous slide, looks decidedly unbalanced and average depth becomes Deletion algorithm described favors making left subtrees deeper than the right (a deleted node is replaced with a node from the right). The exact effect of this still unknown, but if insertions and deletions are alternated Ɵ (N 2 ) times, expected depth is.In the absence of deletions or when lazy deletion is used; average running times for BST operations are O(log N).