Binary Search Trees Berlin Chen 陳柏琳 台灣師範大學資工系 副教授 參考資料來源:

Slides:



Advertisements
Similar presentations
Lecture 15. Graph Algorithms
Advertisements

Algorithms (and Datastructures) Lecture 3 MAS 714 part 2 Hartmut Klauck.
§5 Minimum Spanning Tree 【 Definition 】 A spanning tree of a graph G is a tree which consists of V( G ) and a subset of E( G ) 〖 Example 〗 A complete.
Bioinformatics Programming 1 EE, NCKU Tien-Hao Chang (Darby Chang)
CHAPTER 6 GRAPHS All the programs in this file are selected from
Review Binary Search Trees Operations on Binary Search Tree
Graph Theory.
Chapter 6. Konigsberg Bridge Problem A river Pregel flows around the island Keniphof and then divides into two. Four land areas A, B, C, D have this river.
CS 206 Introduction to Computer Science II 03 / 27 / 2009 Instructor: Michael Eckmann.
TECH Computer Science Graphs and Graph Traversals  // From Tree to Graph  // Many programs can be cast as problems on graph Definitions and Representations.
© 2006 Pearson Addison-Wesley. All rights reserved14 A-1 Chapter 14 excerpts Graphs (breadth-first-search)
Data Structures Using C++
Edited by Malak Abdullah Jordan University of Science and Technology Data Structures Using C++ 2E Chapter 12 Graphs.
CS 206 Introduction to Computer Science II 11 / 11 / Veterans Day Instructor: Michael Eckmann.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 21: Graphs.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Graphs.
Lists A list is a finite, ordered sequence of data items. Two Implementations –Arrays –Linked Lists.
Introduction to Graphs
CS 206 Introduction to Computer Science II 11 / 03 / 2008 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 11 / 05 / 2008 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 03 / 25 / 2009 Instructor: Michael Eckmann.
CS Data Structures Chapter 6 Graphs.
CS 206 Introduction to Computer Science II 11 / 09 / 2009 Instructor: Michael Eckmann.
C. Y. Tang and J. S. Roger Jang
Graph Algorithms Using Depth First Search Prepared by John Reif, Ph.D. Distinguished Professor of Computer Science Duke University Analysis of Algorithms.
C o n f i d e n t i a l HOME NEXT Subject Name: Data Structure Using C Unit Title: Graphs.
GRAPHS Education is what remains after one has forgotten what one has learned in school. Albert Einstein Albert Einstein Smitha N Pai.
Data Structures Using C++ 2E
IS 2610: Data Structures Graph April 5, 2004.
Graphs. Motivating Problem Konigsberg bridge problem (1736): Konigsberg bridge problem (1736): C A B D ab c d e f g Starting in one land area, is it possible.
Copyright Networking Laboratory Chapter 6. GRAPHS Horowitz, Sahni, and Anderson-Freed Fundamentals of Data Structures in C, 2nd Edition Computer.
Been-Chian Chien, Wei-Pang Yang, and Wen-Yang Lin 6-1 Chapter 6 Graphs Introduction to Data Structure CHAPTER 6 GRAPHS 6.1 The Graph Abstract Data Type.
Chapter 2 Graph Algorithms.
GRAPHS CSE, POSTECH. Chapter 16 covers the following topics Graph terminology: vertex, edge, adjacent, incident, degree, cycle, path, connected component,
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
© 2015 JW Ryder CSCI 203 Data Structures1. © 2015 JW Ryder CSCI 203 Data Structures2.
Graphs. What is a graph? A data structure that consists of a set of nodes (vertices) and a set of edges that relate the nodes to each other The set of.
 What is a graph? What is a graph?  Directed vs. undirected graphs Directed vs. undirected graphs  Trees vs graphs Trees vs graphs  Terminology: Degree.
CSCI 115 Chapter 7 Trees. CSCI 115 §7.1 Trees §7.1 – Trees TREE –Let T be a relation on a set A. T is a tree if there exists a vertex v 0 in A s.t. there.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Graphs.
Graphs. Definitions A graph is two sets. A graph is two sets. –A set of nodes or vertices V –A set of edges E Edges connect nodes. Edges connect nodes.
5.5.2 M inimum spanning trees  Definition 24: A minimum spanning tree in a connected weighted graph is a spanning tree that has the smallest possible.
Graphs A graphs is an abstract representation of a set of objects, called vertices or nodes, where some pairs of the objects are connected by links, called.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 13: Graphs Data Abstraction & Problem Solving with C++
1 Directed Graphs Chapter 8. 2 Objectives You will be able to: Say what a directed graph is. Describe two ways to represent a directed graph: Adjacency.
COSC 2007 Data Structures II
GRAPHS. Graph Graph terminology: vertex, edge, adjacent, incident, degree, cycle, path, connected component, spanning tree Types of graphs: undirected,
© 2006 Pearson Addison-Wesley. All rights reserved 14 A-1 Chapter 14 Graphs.
Chapter 6 Graphs. 2 Outline Definitions, Terminologies and Applications Graph Representation Elementary graph operations Famous Graph Problems.
Graphs Upon completion you will be able to:
Graph and Digraph Sung Yong Shin TC Lab. CS Dept., KAIST.
Union By Rank Ackermann’s Function Graph Algorithms Rajee S Ramanikanthan Kavya Reddy Musani.
Graphs 2015, Fall Pusan National University Ki-Joune Li.
Graphs and Paths : Chapter 15 Saurav Karmakar
Chapter 20: Graphs. Objectives In this chapter, you will: – Learn about graphs – Become familiar with the basic terminology of graph theory – Discover.
Graph Representations And Traversals. Graphs Graph : – Set of Vertices (Nodes) – Set of Edges connecting vertices (u, v) : edge connecting Origin: u Destination:
Data Structures and Algorithm Analysis Graph Algorithms Lecturer: Jing Liu Homepage:
Lecture #13. Topics 1.The Graph Abstract Data Type. 2.Graph Representations. 3.Elementary Graph Operations.
Graphs. What is a graph? In simple words, A graph is a set of vertices and edges which connect them. A node (or vertex) is a discrete position in the.
BCA-II Data Structure Using C Submitted By: Veenu Saini
Data Structures 13th Week
Chapter 5 : Trees.
CHAPTER 6 GRAPHS All the programs in this file are selected from
Graphs Chapter 11 Objectives Upon completion you will be able to:
6.1.3 Graph representation.
Graphs.
What is a Graph? a b c d e V= {a,b,c,d,e} E= {(a,b),(a,c),(a,d),
Important Problem Types and Fundamental Data Structures
Chapter 14 Graphs © 2011 Pearson Addison-Wesley. All rights reserved.
INTRODUCTION A graph G=(V,E) consists of a finite non empty set of vertices V , and a finite set of edges E which connect pairs of vertices .
Presentation transcript:

Binary Search Trees Berlin Chen 陳柏琳 台灣師範大學資工系 副教授 參考資料來源:

2 Binary Search Tree Binary search tree – Every element has a unique key –The keys in a nonempty left subtree (right subtree) are smaller (larger) than the key in the root of subtree –The left and right subtrees are also binary search trees A recursive definition!

3 Searching a Binary Search Tree tree_pointer search(tree_pointer root, int key) { /* return a pointer to the node that contains key. If there is no such node, return NULL */ if (!root) return NULL; if (key == root->data) return root; if (key data) return search(root->left_child, key); return search(root->right_child,key); } A Recursive Version Each tree node: - A key value (data) - Two pointers to it left and right children Complexity: O(h)

4 Searching a Binary Search Tree tree_pointer search2(tree_pointer tree, int key) { while (tree) { if (key == tree->data) return tree; if (key data) tree = tree->left_child; else tree = tree->right_child; } return NULL; } A Iterative Version

5 Searching a Binary Search Tree Search by rank permitted if –Each node have an additional field LeftSize which is 1 plus the number of elements in the left subtree of the node tree_pointer search3(tree_pointer tree, int rank) { while (tree) { if (rank == tree->LeftSize) return tree; if (rank LeftSize) tree = tree->left_child; else { rank-= tree->LeftSize; tree = tree->right_child; } return NULL; }

6 Insert Node in Binary Search Tree Insert 80 Insert 35

7 Insertion into A Binary Search Tree void insert_node(tree_pointer *node, int num) {tree_pointer ptr, temp = modified_search(*node, num); if (temp || !(*node)) { ptr = (tree_pointer) malloc(sizeof(node)); if (IS_FULL(ptr)) { fprintf(stderr, “The memory is full\n”); exit(1); } ptr->data = num; ptr->left_child = ptr->right_child = NULL; if (*node) if (num data) temp->left_child=ptr; else temp->right_child = ptr; else *node = ptr; } // Not NULL // Return last visited tree node

8 Deletion for A Binary Search Tree Delete a leaf node –The left (or right) child field of its parent is set to 0 and the node is simply disposed Delete 35 Delete

9 Deletion for A Binary Search Tree Delete a nonleaf node with only one child –The node is deleted and the single-child takes the place of the disposed node Delete

10 Deletion for A Binary Search Tree Delete a nonleaf node with only one child 2 T1 T2 1 X 1 T1

11 Deletion for A Binary Search Tree Delete a nonleaf node that has two children –The largest element in its left subtree or the smallest one in the right tree will replace the disposed mode Delete or

12 Deletion for A Binary Search Tree Delete a nonleaf node that has two children –Recursive adjustments might happen Before deleting 60 After deleting 60

13 Exercise Implement a binary search which is equipped with –Insertion operation –Search operation Search by key Search by Rank –Deletion operation

14 Trie A D C B E F G H I JK Tree A B C G H D K J E F I Trie struct DEF_TREE { int Key; struct Tree *Child; struct Tree *Brother; struct Tree *Father; };

15 Graphs Berlin Chen 陳柏琳 台灣師範大學資工所 助理教授 參考資料來源:

16 Definition A graph G consists of two sets –A finite, nonempty set of vertices V(G) –A finite, possible empty set of edges E(G) –G(V,E) represents a graph An undirected graph (graph) is one in which the pair of vertices in a edge is unordered, (v 0, v 1 ) = (v 1,v 0 ) A directed graph (digraph) is one in which each edge is a directed pair of vertices, != tail head

17 Examples for Graph G1G1 G2G2 G3G3 V(G 1 )={0,1,2,3} E(G 1 )={(0,1),(0,2),(0,3),(1,2),(1,3),(2,3)} V(G 2 )={0,1,2,3,4,5,6} E(G 2 )={(0,1),(0,2),(1,3),(1,4),(2,5),(2,6)} V(G 3 )={0,1,2} E(G 3 )={,, } complete undirected graph: n(n-1)/2 edges complete directed graph: n(n-1) edges complete graph incomplete graph

18 Complete Graph A complete graph is a graph that has the maximum number of edges –For undirected graph with n vertices, the maximum number of edges is n(n-1)/2 –For directed graph with n vertices, the maximum number of edges is n(n-1) –Example: G1 is a complete graph G1G1 complete graph

19 Adjacent and Incident If (v 0, v 1 ) is an edge in an undirected graph –v 0 and v 1 are adjacent –The edge (v 0, v 1 ) is incident on vertices v 0 and v 1 If is an edge in a directed graph –v 0 is adjacent to v 1, and v 1 is adjacent from v 0 –The edge is incident on v 0 and v G3G G2G2

20 Loop and Multigraph Example of a graph with feedback loops and a multigraph (Figure 6.3) –Edges of the form (v, v) or : self edge or self loop 02 1 (a) (b) self edge multigraph: multiple occurrences of the same edge

21 Subgraph and Path A subgraph of G is a graph G’ such that V(G’) is a subset of V(G) and E(G’) is a subset of E(G) A path from vertex v p to vertex v q in a graph G, is a sequence of vertices, v p, v i 1, v i 2,..., v i n, v q, such that (v p, v i 1 ), (v i 1, v i 2 ),..., (v i n, v q ) are edges in an undirected graph The length of a path is the number of edges on it

(i) (ii) (iii) (iv) (a) Some of the subgraph of G (i) (ii) (iii) (iv) (b) Some of the subgraph of G 3 分開 單一 G1G G3G3 Figure 6.4: subgraphs of G 1 and G 3

23 Simple Path and Cycle A simple path is a path in which all vertices except possibly the first and the last are distinct A cycle is a simple path in which the first and the last vertices are the same In an undirected graph G, two vertices, v 0 and v 1, are connected if there is a path in G from v 0 to v 1 An undirected graph is connected if, for every pair of distinct vertices v i, v j, there is a path from v i to v j

G1G1 G2G2 connected tree (acyclic graph)

25 Connected Component A connected component of an undirected graph is a maximal connected subgraph A tree is a graph that is connected and acyclic A directed graph is strongly connected if there is a directed path from v i to v j and also from v j to v i A strongly connected component is a maximal subgraph that is strongly connected

26 Figure 6.5: A graph with two connected components H1H1 H2H2 G 4 (not connected) connected component (maximal connected subgraph)

27 Figure 6.6: Strongly connected components of G G3G3 not strongly connected strongly connected component (maximal strongly connected subgraph)

28 Degree The degree of a vertex is the number of edges incident to that vertex For directed graph, –the in-degree of a vertex v is the number of edges that have v as the head –the out-degree of a vertex v is the number of edges that have v as the tail –if d i is the degree of a vertex i in a graph G with n vertices and e edges, the number of edges is

29 undirected graph degree G1G1 G2G directed graph in-degree out-degree G3G3 in:1, out: 1 in: 1, out: 2 in: 1, out:

30 ADT for Undirected Graph structure Graph is objects: a nonempty set of vertices and a set of undirected edges, where each edge is a pair of vertices functions: for all graph  Graph, v, v 1 and v 2  Vertices Graph Create()::=return an empty graph Graph InsertVertex(graph, v)::= return a graph with v inserted. v has no incident edge Graph InsertEdge(graph, v 1,v 2 )::= return a graph with new edge between v 1 and v 2 Graph DeleteVertex(graph, v)::= return a graph in which v and all edges incident to it are removed Graph DeleteEdge(graph, v 1, v 2 )::=return a graph in which the edge (v 1, v 2 ) is removed Boolean IsEmpty(graph)::= if (graph==empty graph) return TRUE else return FALSE List Adjacent(graph,v)::= return a list of all vertices that are adjacent to v

31 Graph Representations Adjacency Matrix Adjacency Lists Adjacency Multilists

32 Adjacency Matrix Let G=(V,E) be a graph with n vertices. The adjacency matrix of G is a two-dimensional n by n array, say adj_mat If the edge (v i, v j ) is in E(G), adj_mat[i][j]=1 If there is no such edge in E(G), adj_mat[i][j]=0 The adjacency matrix for an undirected graph is symmetric; the adjacency matrix for a digraph need not be symmetric

33 Examples for Adjacency Matrix G1G1 G2G2 G4G symmetric undirected: n 2 /2 directed: n 2

34 Merits of Adjacency Matrix From the adjacency matrix, to determine the connection of vertices is easy The degree of a vertex is For a digraph, the row sum is the out_degree, while the column sum is the in_degree sum up a column sum up a row

35 Data Structures for Adjacency Lists #define MAX_VERTICES 50 typedef struct node *node_pointer; typedef struct node { int vertex; struct node *link; }; node_pointer graph[MAX_VERTICES]; int n=0; /* vertices currently in use */ Each row in adjacency matrix is represented as an adjacency list

G1G G3G G4G An undirected graph with n vertices and e edges ==> n head nodes and 2e list nodes

37 Interesting Operations Degree of a vertex in an undirected graph –Number of nodes in adjacency list Number of edges in a graph –Determined in O(n+e) Out-degree of a vertex in a directed graph (digraph) –Number of nodes in its adjacency list In-degree of a vertex in a directed graph (digraph) –Traverse the whole data structure –Or maintained in inversed adjacency lists

38 Compact Representation node[0] … node[n-1]: starting point for vertices node[n]: n+2e+1 (upper bound of the array) The vertices adjacent from vertex i are stored in array indexed from node[i] to node[i+1]-1

39 Inverse Adjacency Lists  NULL 0 NULL 1 NULL Determine in-degree of a vertex in a fast way. Figure 6.10: Inverse adjacency lists for G 3

40 A simplified version of the list structure for sparse matrix representation tail head column link for head row link for tail Figure 6.11: Alternate node structure for adjacency lists Information for an edge for in-degree information for out-degree information

NULL NULL 0 1 NULL NULL 1 2 NULL NULL Figure 6.12: Orthogonal representation for graph G 3 head nodes (shown twice)

42  3  2 NULL 1  0  2  3 NULL 0  1  3  1 NULL 0  2  2  0 NULL 1  3 headnodes vertax link Order is of no significance Figure 6.13:Alternate order adjacency list for G 1

43 Exercise P. 344 Exercises 2, 10

44 Adjacency Multilists An edge in an undirected graph is represented by two nodes in adjacency list representation. Adjacency Multilists –lists in which nodes may be shared among several lists (an edge is shared by two different paths) m vertex1 vertex2 list1 list2 A Boolean mark indicating whether or not the edge has been examined

45 Example for Adjacency Multlists Lists: vertex 0: N0->N1->N2 vertex 1: N0->N3->N4 vertex 2: N1->N3->N5 vertex 3: N2->N4->N5 0 1 N1 N3 0 2 N2 N3 0 3 N4 1 2 N4 N5 1 3 N5 2 3 N0 N1 N2 N3 N4 N edge (0,1) edge (0,2) edge (0,3) edge (1,2) edge (1,3) edge (2,3) (1,0) (2,0) (3,0) (2,1) (3,1) (3,2) six edges

46 Some Graph Operations Traversal Given G=(V,E) and vertex v, find all w  V, such that w connects v –Depth First Search (DFS) preorder tree traversal –Breadth First Search (BFS) level order tree traversal Connected Components Spanning Trees

47 Example: Graph G and its adjacency lists depth first search: v0, v1, v3, v7, v4, v5, v2, v6 breadth first search: v0, v1, v2, v3, v4, v5, v6, v7 Figure 6.16: visit all vertices in G that are reachable form v0

48 Depth First Search (DFS, dfs) void dfs(int v) { node_pointer w; visited[v]= TRUE; printf(“%5d”, v); for (w=graph[v]; w; w=w->link) if (!visited[w->vertex]) dfs(w->vertex); } #define FALSE 0 #define TRUE 1 short int visited[MAX_VERTICES]; Data structure adjacency list: O(e) adjacency matrix: O(n 2 ) A Recursive Function

49 Breadth First Search (BFS, bfs) typedef struct queue *queue_pointer; typedef struct queue { int vertex; queue_pointer link; }; void addq(queue_pointer *, queue_pointer *, int); int deleteq(queue_pointer *);

50 Breadth First Search void bfs(int v) { node_pointer w; queue_pointer front, rear; front = rear = NULL; printf(“%5d”, v); visited[v] = TRUE; addq(&front, &rear, v); adjacency list: O(e) adjacency matrix: O(n 2 ) while (front) { v= deleteq(&front); for (w=graph[v]; w; w=w->link) if (!visited[w->vertex]) { printf(“%5d”, w->vertex); addq(&front, &rear, w->vertex); visited[w->vertex] = TRUE; }

51 Connected Components void connected(void) { for (i=0; i<n; i++) visited[i]=0; for (i=0; i<n; i++) { if (!visited[i]) { dfs(i); printf(“\n”); } adjacency list: O(n+e) adjacency matrix: O(n 2 )

52 Exercise Implement DFS and BFS Implement a function to determine the connected components for a graph

53 Spanning Trees When graph G is connected, a depth first or breadth first search starting at any vertex will visit all vertices in G –Form a tree that includes all the vertices of G A spanning tree is any tree that consists solely of edges in G and that includes all the vertices E(G): T (tree edges) + N (nontree edges) where T: set of edges used during search N: set of remaining edges

54 Examples of Spanning Tree G1G1 Possible spanning trees

55 Spanning Trees Either DFS or BFS can be used to create a spanning tree –When DFS is used, the resulting spanning tree is known as a depth first spanning tree –When BFS is used, the resulting spanning tree is known as a breadth first spanning tree While adding a nontree edge into any spanning tree, this will create a cycle

56 DFS VS. BFS Spanning Tree DFS Spanning BFS Spanning nontree edge cycle

57 Biconnected Graph A spanning tree is a minimal subgraph, G’, of G such that V(G’)=V(G) and G’ is connected Any connected graph with n vertices must have at least n-1 edges A biconnected graph is a connected graph that has no articulation points biconnected graph

58 Articulation Point A vertex v is an articulation point iff the deletion of v, together with the deletion of all edges incident to v, leaves behind a graph has at least two connected components

59 biconnected component: a maximal connected subgraph H (no subgraph that is both biconnected and properly contains H) biconnected components Two biconnected components can at most have one vertex at common

60 Find biconnected component of a connected undirected graph by depth first spanning tree (a) depth first spanning tree (b) 2 2 dfn depth first number nontree edge (back edge) nontree edge (back edge) If u is an ancestor of v then dfn(u) < dfn(v)

61 Minimum Cost Spanning Tree The cost of a spanning tree of a weighted undirected graph is the sum of the costs of the edges in the spanning tree A minimum cost spanning tree is a spanning tree of least cost Three different algorithms can be used –Kruskal –Prim –Sollin Select n-1 edges from a weighted graph of n vertices with minimum cost.

62 Greedy Strategy An optimal solution is constructed in stages At each stage, the best decision is made at this time Since this decision cannot be changed later, we make sure that the decision will result in a feasible solution Typically, the selection of an item at each stage is based on a least cost or a highest profit criterion

63 Kruskal’s Idea Build a minimum cost spanning tree T by adding edges to T one at a time Select the edges for inclusion in T in nondecreasing order of the cost An edge is added to T if it does not form a cycle Since G is connected and has n > 0 vertices, exactly n-1 edges will be selected

64 Examples for Kruskal’s Algorithm /9

65 Examples for Kruskal’s Algorithm cycle

66 Examples for Kruskal’s Algorithm cycle + cost =

67 Kruskal’s Algorithm T= {}; while (T contains less than n-1 edges && E is not empty) { choose a least cost edge (v,w) from E; delete (v,w) from E; if ((v,w) does not create a cycle in T) add (v,w) to T else discard (v,w); } if (T contains fewer than n-1 edges) printf(“No spanning tree\n”);

68 Exercise The missionaries and cannibals problem is usually stated as follows. Three missionaries and three cannibals are on one side of a river, along with a boat that can hold one or two people. Find a way to get every one to the other side, without leaving a group of missionaries in one place outnumbered by the cannibals in that place.