CPS 100 4.1 Scoreboard l What else might we want to do with a data structure? l What are maps’ limitations? AlgorithmInsertionDeletionSearch Unsorted.

Slides:



Advertisements
Similar presentations
S. Sudarshan Based partly on material from Fawzi Emad & Chau-Wen Tseng
Advertisements

Binary Search Trees. John Edgar  Understand tree terminology  Understand and implement tree traversals  Define the binary search tree property  Implement.
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.
Binary Trees Terminology A graph G = is a collection of nodes and edges. An edge (v 1,v 2 ) is a pair of vertices that are directly connected. A path,
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.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Data Structures Using C++ 2E Chapter 11 Binary Trees and B-Trees.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 20: Binary Trees.
1 Joe Meehean.  Important and common problem  Given a collection, determine whether value v is a member  Common variation given a collection of unique.
Data Structures Using C++1 Chapter 11 Binary Trees.
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.
CPS Wordcounting, sets, and the web l How does Google store all web pages that include a reference to “peanut butter with mustard”  What efficiency.
Chapter 19: Binary Trees. Objectives In this chapter, you will: – Learn about binary trees – Explore various binary tree traversal algorithms – Organize.
CPS 100, Spring Trees: no data structure lovelier?
Searching: Binary Trees and Hash Tables CHAPTER 12 6/4/15 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,
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.
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 ),
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
CompSci 100e Program Design and Analysis II March 29, 2011 Prof. Rodger CompSci 100e, Spring20111.
1 Chapter 10 Trees. 2 Definition of Tree A tree is a set of linked nodes, such that there is one and only one path from a unique node (called the root.
Trees, Binary Trees, and Binary Search Trees COMP171.
 Trees Data Structures Trees Data Structures  Trees Trees  Binary Search Trees Binary Search Trees  Binary Tree Implementation Binary Tree Implementation.
CompSci 100e 7.1 From doubly-linked lists to binary trees l Instead of using prev and next to point to a linear arrangement, use them to divide the universe.
CompSci 100e 7.1 Plan for the week l Review:  Union-Find l Understand linked lists from the bottom up and top-down  As clients of java.util.LinkedList.
Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.
M180: Data Structures & Algorithms in Java Trees & Binary Trees Arab Open University 1.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
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.
Binary Search Trees (BST)
Binary Search Trees.  Understand tree terminology  Understand and implement tree traversals  Define the binary search tree property  Implement binary.
1 Joe Meehean. A A B B D D I I C C E E X X A A B B D D I I C C E E X X  Terminology each circle is a node pointers are edges topmost node is the root.
CMSC 202, Version 5/02 1 Trees. CMSC 202, Version 5/02 2 Tree Basics 1.A tree is a set of nodes. 2.A tree may be empty (i.e., contain no nodes). 3.If.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
Search: Binary Search Trees Dr. Yingwu Zhu. Review: Linear Search Collection of data items to be searched is organized in a list x 1, x 2, … x n – Assume.
1 Trees : Part 1 Reading: Section 4.1 Theory and Terminology Preorder, Postorder and Levelorder Traversals.
Trees By JJ Shepherd. Introduction Last time we discussed searching and sorting in a more efficient way Divide and Conquer – Binary Search – Merge Sort.
Trees CSIT 402 Data Structures II 1. 2 Why Do We Need Trees? Lists, Stacks, and Queues are linear relationships Information often contains hierarchical.
CSE 373 Data Structures Lecture 7
From doubly-linked lists to binary trees
Non Linear Data Structure
Trees Chapter 15.
Data Structure and Algorithms
CSCE 210 Data Structures and Algorithms
Printing a search tree in order
Chapter 5 : Trees.
PFTFBH Binary Search trees Fundamental Data Structure
Binary Trees Linked lists: efficient insertion/deletion, inefficient search ArrayList: search can be efficient, insertion/deletion not Binary trees: efficient.
Binary Trees Linked lists: efficient insertion/deletion, inefficient search ArrayList: search can be efficient, insertion/deletion not Binary trees: efficient.
UNIT III TREES.
What’s the Difference Here?
CMSC 341 Introduction to Trees.
CSE 373 Data Structures Lecture 7
abstract containers sequence/linear (1 to 1) hierarchical (1 to many)
ITEC 2620M Introduction to Data Structures
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.
Find in a linked list? first last 7  4  3  8 NULL
common code “abstracted out” same code written several times: don’t!
Binary Trees, Binary Search Trees
Trees.
Trees.
Binary Trees, Binary Search Trees
Data Structures Using C++ 2E
Presentation transcript:

CPS Scoreboard l What else might we want to do with a data structure? l What are maps’ limitations? AlgorithmInsertionDeletionSearch Unsorted Vector/array Sorted vector/array Linked list Sorted linked lists Doubly-linked/circular linked lists Hash Maps

CPS Graphs: Structures and Algorithms l How do packets of bits/information get routed on the internet ä Message divided into packets on client (your) machine ä Packets sent out using routing tables toward destination Packets may take different routes to destination What happens if packets lost or arrive out-of-order? ä Routing tables store local information, not global (why?) l What about The Oracle of Bacon, Six Degrees of Separation, Erdos Numbers, and Word Ladders?The Oracle of BaconSix Degrees of Separation Erdos Numbers ä All can be modeled using graphs ä What kind of connectivity does each concept model? l Graphs are everywhere in the world of algorithms (world?)

CPS Vocabulary l Graphs are collections of vertices and edges ä Vertex is sometimes called a node ä An edge connects two vertices Direction is sometimes important, other times not so Sometimes edge has a weight/cost associated with it l A sequence of vertices v 0, v 1, v 2, …, v n-1 is a path where v k and v k+1 are connected by an edge. ä If some vertex is repeated, the path is a cycle ä Trees are cycle-free graphs with a root ä Nodes have in-degree and out-degree Number of edges entering or leaving a node Binary trees are acyclic rooted graphs where the nodes have out-degree <= 2 and in-degree = 1 for all nodes besides root

CPS Binary Trees l Binary trees are structures that yield efficient insertion, deletion, and search ä trees used in many contexts, not just for searching, e.g., expression trees ä insertion is as efficient as binary search in array, insertion/deletion as efficient as linked list (once node found) ä binary trees are inherently recursive, difficult to process trees non-recursively, but possible (recursion never required, but often makes coding/algorithms simpler)

CPS From doubly-linked lists to binary trees l Instead of using prev and next to point to a linear arrangement, use them to divide the universe in half ä Similar to binary search, everything less goes left, everything greater goes right ä How do we search? ä How do we insert? ä How are lists and trees related? “llama” “tiger” “monkey” “jaguar” “elephant” “ giraffe ” “pig” “hippo” “leopard”

CPS Basic tree definitions l Binary tree is a structure: ä empty ä root node with left and right subtrees l terminology: parent, children, leaf node, internal node, depth, height, path link from node N to M then N is parent of M –M is child of N leaf node has no children –internal node has 1 or 2 children path is sequence of nodes, N 1, N 2, … N k –N i is parent of N i+1 –sometimes edge instead of node depth (level) of node: length of root-to-node path –level of root is 1 height of node: length of longest node-to-leaf path –height of tree is height of root A B ED F C G

CPS Printing a search tree in order l When is root printed? ä After left subtree, before right subtree. void Visit(Node * t) { if (t != 0) { Visit(t->prev); cout info << endl; Visit(t->next); } l Inorder traversal “llama” “tiger” “monkey” “jaguar” “elephant” “ giraffe ” “pig” “hippo” “leopard”

CPS Insertion and Find? Complexity? l How do we search for a value in a tree, starting at root? ä Can do this both iteratively and recursively, contrast to printing which is very difficult to do iteratively ä How is insertion similar to search? l What is complexity of print? Of insertion? ä Is there a worst case for trees? ä Do we use best case? Worst case? Average case? l How do we define worst and average cases ä For trees? For vectors? For different implementations of multiset (append, prepend, move-to-front)

CPS From concept to code with binary trees l Trees can have many shapes: short/bushy, long/stringy  if height is h, number of nodes is between h and 2 h -1 ä single node tree: height = 1, if height = 3 ä C++ implementation, similar to doubly-linked list struct Tree { string info; Tree * left; Tree * right; Tree(const string& s, Tree * lptr, Tree * rptr) : info(s), left(lptr), right(rptr) { } };

CPS Tree functions l Compute height of a tree, what is complexity? int height(Tree * root) { if (root == 0) return ; else { return 1 + max(height(root->left), height(root->right) ); } l Modify function to compute number of nodes in a tree, does complexity change? ä What about computing number of leaf nodes?

CPS Tree traversals l Different traversals useful in different contexts ä Inorder prints search tree in order Visit left-subtree, process root, visit right-subtree ä Preorder useful for reading/writing trees Process root, visit left-subtree, visit right-subtree ä Postorder useful for destroying trees Visit left-subtree, visit right-subtree, process root “llama” “tiger” “monkey” “jaguar” “elephant” “ giraffe ”

CPS Insertion into search tree l Simple recursive insertion into tree void insert(Tree *& t, const string& s) // pre: t is a search tree // post: s inserted into t, t is a search tree { if (t == 0) t = new Tree(s,0,0); else if (s left) insert(t->left,s); else insert(t->right,s); } l Note: in each recursive call, the parameter t in the called clone is either the left or right pointer of some node in the original tree ä Why is this important? ä Why must t be passed by reference?  For alternatives see basictree.cpp

CPS Balanced Trees and Complexity l A tree is height-balanced if ä Left and right subtrees are height-balanced ä Left and right heights differ by at most one bool isBalanced(Tree * root) { if (root == 0) return true; else { return isBalanced(root->left) && isBalanced(root->right) && abs(height(root->left) – height(root->right)) <= 1; }

CPS What is complexity? l Assume trees are “balanced” in analyzing complexity ä Roughly half the nodes in each subtree ä Leads to easier analysis l How to develop recurrence relation? ä What is T(n)? ä What other work is done? l How to solve recurrence relation ä Plug, expand, plug, expand, find pattern ä A real proof requires induction to verify that pattern is correct

CPS sidebar: solving recurrence T(n) = 2T(n/2) + O(n) T() = 2T(/2) + T(1) = 1 what about 2n? 3n? T(n) = 2[2T(n/4) + n/2] + n = 4 T(n/4) + n + n = 4[2T(n/8) + n/4] + 2n = 8T(n/8) + 3n =... eureka! = 2 k T(n/2 k ) + kn let 2 k = n k = log n, this yields 2 log n T(n/2 log n ) + n(log n) n T(1) + n(log n) O(n log n)

CPS Class implementation issues: trees l Consider a class Set implemented using search trees ä Could develop a search tree class, could use “raw” nodes in implementing the set ä For tree class, exposing Nodes to client programs makes coding more simple than encapsulating tree We view trees/nodes as a concrete implementation Client classes/code manipulate trees via pointers Other alternatives exist, (i.e., complete encapsulation) l Many tree functions are recursive, parameter is a Node/Tree ä Don’t want clients of ADT to know trees used, therefore cannot have public functions with Node params ä Alternative? Private helper function called by public

CPS Simple header file with helper functions class TreeSet { public: TreeSet(); bool add(const string& word); void print() const; private: struct Node { string info; Node * left * right; }; void addHelp (Node *& root, const string& word); void printHelp(Node * root) const; Node * myRoot; };

CPS Private helper functions to the rescue void TreeSet::print() const { printHelp(myRoot); } void TreeSet::printHelp(Node * root) const { // standard inorder traversal } l Why is helper function necessary? Is it really necessary? ä Alternatives for other functions: insert, for example  What about const-ness for public/private functions?

CPS Deleting a node from a tree l Deleting nodes is tricky ä What about gopher, leopard? ä What about monkey? ä What about jaguar? l Delete giraffe? ä Minimize moved nodes ä Possibilities? l Use inorder successor as replacement, guaranteed at most one child ä Where is it, why only one child? “llama” “tiger” “monkey” “jaguar” “elephant” “ giraffe ” “pig” “hippo” “leopard” “iguana” “gopher”