Propedéutico de Programación

Similar documents
8 Binary Search Trees

Chapter 8. Binary Search Trees. Fall 2013 Yanjun Li CISC Trees. Owner Jake. Waitress Waiter Cook Helper Joyce Chris Max Len

Homework Assignment #3

Propedéutico de Programación

template<class T> T TreeNode<T>:: getdata() const { return data; }//end getdata

SCJ2013 Data Structure & Algorithms. Binary Search Tree. Nor Bahiah Hj Ahmad

Chapter 20: Binary Trees

Propedéutico de Programación

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

Propedéutico de Programación

CSCI-401 Examlet #5. Name: Class: Date: True/False Indicate whether the sentence or statement is true or false.

Propedéutico de Programación

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

CS350: Data Structures Tree Traversal

Tree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example.

Binary Trees. Examples:

CSI33 Data Structures

Binary Trees and Binary Search Trees

Data Structures. Trees. By Dr. Mohammad Ali H. Eljinini. M.A. Eljinini, PhD

CS302 - Data Structures using C++

a graph is a data structure made up of nodes in graph theory the links are normally called edges

Binary Search Trees. See Section 11.1 of the text.

void insert( Type const & ) void push_front( Type const & )

BINARY SEARCH TREES. Problem Solving with Computers-II

Binary Trees Fall 2018 Margaret Reid-Miller

Tree Structures. A hierarchical data structure whose point of entry is the root node

Trees. (Trees) Data Structures and Programming Spring / 28

Discussion 2C Notes (Week 8, February 25) TA: Brian Choi Section Webpage:

Binary Tree. Binary tree terminology. Binary tree terminology Definition and Applications of Binary Trees

Binary Trees, Binary Search Trees

TREES. Trees - Introduction

A set of nodes (or vertices) with a single starting point

* Due 11:59pm on Sunday 10/4 for Monday lab and Tuesday 10/6 Wednesday Lab

Trees 11/15/16. Chapter 11. Terminology. Terminology. Terminology. Terminology. Terminology

Abstract Data Structures IB Computer Science. Content developed by Dartford Grammar School Computer Science Department

Binary Trees

BST Implementation. Data Structures. Lecture 4 Binary search trees (BST) Dr. Mahmoud Attia Sakr University of Ain Shams

Section 5.5. Left subtree The left subtree of a vertex V on a binary tree is the graph formed by the left child L of V, the descendents

Trees. 1 Introduction. 2 Trees. Prof. Stewart Weiss. CSci 235 Software Design and Analysis II Trees

Cpt S 122 Data Structures. Data Structures Trees

BINARY SEARCH TREES (CONTD) Problem Solving with Computers-II

Trees, Binary Trees, and Binary Search Trees

Programming II (CS300)

Chapter 11.!!!!Trees! 2011 Pearson Addison-Wesley. All rights reserved 11 A-1

Chapter 11.!!!!Trees! 2011 Pearson Addison-Wesley. All rights reserved 11 A-1

Chapter 5. Binary Trees

3 Trees: traversal and analysis of standard search trees. Summer Term 2010

Tree Applications. Processing sentences (computer programs or natural languages) Searchable data structures

3 Trees: traversal and analysis of standard search trees

LECTURE 13 BINARY TREES

CMSC 341 Lecture 10 Binary Search Trees

Anexos. Diseño y construcción de un puente grúa automatizado de precisión

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

Partha Sarathi Mandal

Binary Trees: Practice Problems

Test 1: CPS 100. Owen Astrachan. October 11, 2000

Trees. Dr. Ronaldo Menezes Hugo Serrano Ronaldo Menezes, Florida Tech

#include "Tree.h" Root = nullptr;

binary tree empty root subtrees Node Children Edge Parent Ancestor Descendant Path Depth Height Level Leaf Node Internal Node Subtree

Data Structures and Algorithms

CS350: Data Structures Binary Search Trees

Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees

STUDENT LESSON AB30 Binary Search Trees

CS 206 Introduction to Computer Science II

Binary Tree. Preview. Binary Tree. Binary Tree. Binary Search Tree 10/2/2017. Binary Tree

Tree Data Structures CSC 221

- 1 - Handout #22S May 24, 2013 Practice Second Midterm Exam Solutions. CS106B Spring 2013

Associate Professor Dr. Raed Ibraheem Hamed

1 Binary trees. 1 Binary search trees. 1 Traversal. 1 Insertion. 1 An empty structure is an empty tree.

Multi-Way Search Tree

Trees. Introduction & Terminology. February 05, 2018 Cinda Heeren / Geoffrey Tien 1

Trees: examples (Family trees)

Why Do We Need Trees?

Data Structure - Binary Tree 1 -

BE ISE 3 rd Semester

What is a List? elements, with a linear relationship. first) has a unique predecessor, and. unique successor.

13 BINARY TREES DATA STRUCTURES AND ALGORITHMS INORDER, PREORDER, POSTORDER TRAVERSALS

CISC 235 Topic 3. General Trees, Binary Trees, Binary Search Trees

Recursion, Binary Trees, and Heaps February 18

CMSC 341. Binary Search Trees CMSC 341 BST

Search Trees. Data and File Structures Laboratory. DFS Lab (ISI) Search Trees 1 / 17

CSE2331/5331. Topic 6: Binary Search Tree. Data structure Operations CSE 2331/5331

March 20/2003 Jayakanth Srinivasan,

CS 308 Data Structures Spring Dr. George Bebis Final Exam

Search Trees: BSTs and B-Trees

CS 350 : Data Structures Binary Search Trees

Trees, Heaps, and Priority Queues

Terminology. The ADT Binary Tree. The ADT Binary Search Tree

Data Structure. Chapter 5 Trees (Part II) Angela Chih-Wei Tang. National Central University Jhongli, Taiwan

Binary Tree Node Relationships. Binary Trees. Quick Application: Expression Trees. Traversals

Binary Trees. For example: Jargon: General Binary Trees. root node. level: internal node. edge. leaf node. Data Structures & File Management

CS302 - Data Structures using C++

[ DATA STRUCTURES ] Fig. (1) : A Tree

CS302 - Data Structures using C++

Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees

Name CPTR246 Spring '17 (100 total points) Exam 3

ECE Spring 2018 Problem Set #0 Due: 1/30/18

Binary Trees. Height 1

C Data Structures Stacks. Stack. push Adds a new node to the top of the stack

Principles of Computer Science

Transcription:

Propedéutico de Programación Coordinación de Ciencias Computacionales Semana 6, Primera Parte Dra. Pilar Gómez Gil Versión 1.2 08.07.08 http://ccc.inaoep.mx/~pgomez/cursos/programacion/

Chapter 8 Binary Search Trees Continuación Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th.

Tree Recursion CountNodes Version 1 if (Left(tree) is NULL) AND (Right(tree) is NULL) else return 1 return CountNodes(Left(tree)) + CountNodes(Right(tree)) + 1 What happens when Left(tree) is NULL?

Tree Recursion CountNodes Version 2 if (Left(tree) is NULL) AND (Right(tree) is NULL) return 1 else if Left(tree) is NULL return CountNodes(Right(tree)) + 1 else if Right(tree) is NULL return CountNodes(Left(tree)) + 1 else return CountNodes(Left(tree)) + CountNodes(Right(tree)) + 1 What happens when the initial tree is NULL?

Tree Recursion CountNodes Version 3 if tree is NULL return 0 else if (Left(tree) is NULL) AND (Right(tree) is NULL) return 1 else if Left(tree) is NULL return CountNodes(Right(tree)) + 1 else if Right(tree) is NULL return CountNodes(Left(tree)) + 1 else return CountNodes(Left(tree)) + CountNodes(Right(tree)) + 1 Can we simplify this algorithm?

Tree Recursion CountNodes Version 4 if tree is NULL return 0 else return CountNodes(Left(tree)) + CountNodes(Right(tree)) + 1 Is that all there is?

// Implementation of Final Version int CountNodes(TreeNode* tree); // Pototype int TreeType::LengthIs() const // Class member function { return CountNodes(root); } int CountNodes(TreeNode* tree) // Recursive function that counts the nodes { if (tree == NULL) return 0; else return CountNodes(tree->left) + CountNodes(tree->right) + 1; } Ed. 2007 Instructor material, Jones & Barlett Publishers

Retrieval Operation

Retrieval Operation void TreeType::RetrieveItem(ItemType& item, bool& found) { Retrieve(root, item, found); } void Retrieve(TreeNode* tree, ItemType& item, bool& found) { if (tree == NULL) found = false; else if (item < tree->info) Retrieve(tree->left, item, found);

Retrieval Operation, cont. else if (item > tree->info) Retrieve(tree->right, item, found); else { item = tree->info; found = true; } }

The Insert Operation A new node is always inserted into its appropriate position in the tree as a leaf.

Insertions into a Binary Search Tree Ed. 2007 Instructor material, Jones & Barlett Publishers

The recursive InsertItem operation Por ejemplo, insertando11 Ed. 2007 Instructor material, Jones & Barlett Publishers

The tree parameter is a pointer within the tree

Recursive Insert void Insert(TreeNode*& tree, ItemType item) { if (tree == NULL) {// Insertion place found. tree = new TreeNode; tree->right = NULL; tree->left = NULL; tree->info = item; } else if (item < tree->info) Insert(tree->left, item); else Insert(tree->right, item); }

Eliminando un Nodo Hay 3 posibles casos: 1. Que el nodo a eliminarse no tenga ningún hijo 2. Que el nodo a eliminarse tenga un hijo 3. Que el nodo a eliminarse tenga dos hijos

Deleting a Leaf Node Caso 1 La eliminación es simplemente limpiar memoria

Deleting a Node with One Child Caso 2 La eliminación consiste en que el hijo toma el lugar del padre

Deleting a Node with Two Children Caso 3 Hay que determinar quien toma el lugar del padre sin que se afecte el árbol Q Ed. 2007 Instructor material, Jones & Barlett Publishers

Para el caso 3 El lugar del padre eliminándose, lo puede tomar su predecesor inmediato o su sucesor inmediato. En éste caso se utiliza al predecesor, el cual es el valor mas grande en el subárbol izquierdo del elemento eliminándose, esto es, el nodo que está mas hacia la derecha en el subárbol izquierdo Ed. 2007 Instructor material, Jones & Barlett Publishers

DeleteNode Algorithm if (Left(tree) is NULL) AND (Right(tree) is NULL) Set tree to NULL else if Left(tree) is NULL Set tree to Right(tree) else if Right(tree) is NULL Set tree to Left(tree) else Find predecessor Set Info(tree) to Info(predecessor) Delete predecessor

Code for DeleteNode void DeleteNode(TreeNode*& tree) { ItemType data; TreeNode* tempptr; tempptr = tree; if (tree->left == NULL) { tree = tree->right; delete tempptr; } else if (tree->right == NULL){ tree = tree->left; delete tempptr;} els{ GetPredecessor(tree->left, data); tree->info = data; Delete(tree->left, data);} } Tomado de: Dale, N. Weems, C++ Plus Data Structures

Pero primero hay que encontrar el nodo a eliminarse recordando: DeleteItem(itemType item) Función: Borra el elemento cuya llave coincide con la llave de item Precondición: La llave de item se inicializó. Uno y solo uno de los elementos en el árbol tiene una llave que coincide con la de item Postcondición: Ningún elemento en el árbol tiene una llave que coincide con la de item

Definition of Recursive Delete Definition: Removes item from tree Size: The number of nodes in the path from the root to the node to be deleted. Base Case: If item's key matches key in Info(tree), delete node pointed to by tree. General Case: If item < Info(tree), Delete(Left(tree), item); else Delete(Right(tree), item).

Código void TreeType::DeleteItem(ItemType item) // Calls recursive function Delete to delete item from tree. { } Delete(root, item); Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Jones & Barlett Publishers

Code for Recursive Delete void Delete(TreeNode*& tree, ItemType item) { if (item < tree->info) Delete(tree->left, item); else if (item > tree->info) Delete(tree->right, item); else DeleteNode(tree); // Node found }

Code for GetPredecessor void GetPredecessor(TreeNode* tree, ItemType& data) { while (tree->right!= NULL) tree = tree->right; data = tree->info; }

Printing all the Nodes in Order

Function Print Definition: Size: Prints the items in the binary search tree in order from smallest to largest. The number of nodes in the tree whose root is tree Base Case: If tree = NULL, do nothing. General Case: Traverse the left subtree in order. Then print Info(tree). Then traverse the right subtree in order.

Code for Recursive InOrder Print void PrintTree(TreeNode* tree, std::ofstream& outfile) { if (tree!= NULL) { PrintTree(tree->left, outfile); outfile << tree->info; PrintTree(tree->right, outfile); } }

Destructor void Destroy(TreeNode*& tree); TreeType::~TreeType() { Destroy(root); } void Destroy(TreeNode*& tree) { if (tree!= NULL) { Destroy(tree->left); Destroy(tree->right); delete tree; } } Ed. 2007 Instructor material, Jones & Barlett Publishers

Algorithm for Copying a Tree if (originaltree is NULL) Set copy to NULL else Set Info(copy) to Info(originalTree) Set Left(copy) to Left(originalTree) Set Right(copy) to Right(originalTree)

Code for CopyTree void CopyTree(TreeNode*& copy, const TreeNode* originaltree) { if (originaltree == NULL) copy = NULL; else { copy = new TreeNode; copy->info = originaltree->info; CopyTree(copy->left, originaltree->left); CopyTree(copy->right, originaltree->right); } } Ed. 2007 Instructor material, Jones & Barlett Publishers

Recorrido recursivo de árboles binarios - Preorder Raíz Árbol Izquierdo Árbol Derecho - Inorder Árbol Izquierdo Raíz Árbol Derecho - Postorder Árbol Izquierdo Árbol Derecho Raíz

if tree is not NULL Inorder(Left(tree)) Visit Info(tree) Inorder(Right(tree)) Inorder(tree) To print in alphabetical order

Postorder(tree) if tree is not NULL Postorder(Left(tree)) Postorder(Right(tree)) Visit Info(tree)

if tree is not NULL Visit Info(tree) Preorder(Left(tree)) Preorder(Right(tree)) Preorder(tree)

Three Tree Traversals Ed. 2007 Instructor material, Jones & Barlett Publishers

Our Iteration Approach The client program passes the ResetTree and GetNextItem functions a parameter indicating which of the three traversals to use ResetTree generates a queues of node contents in the indicated order GetNextItem processes the node contents from the appropriate queue: inque, preque, postque.

Code for ResetTree void TreeType::ResetTree(OrderType order) // Calls function to create a queue of the tree // elements in the desired order. { switch (order) { case PRE_ORDER : PreOrder(root, preque); break; case IN_ORDER : InOrder(root, inque); break; case POST_ORDER: PostOrder(root, postque); break; } }

Code for GetNextItem void TreeType::GetNextItem(ItemType& item, OrderType order,bool& finished) { finished = false; switch (order) { case PRE_ORDER : preque.dequeue(item); if (preque.isempty()) finished = true; break; case IN_ORDER : inque.dequeue(item); if (inque.isempty()) finished = true; break; case POST_ORDER: postque.dequeue(item); if (postque.isempty()) finished = true; break; } }

Ver TreeType.h TreeType.cpp