Binary Trees. Directed, Rooted Tree. Terminology. Trees. Binary Trees. Possible Implementation 4/18/2013

Similar documents
Data Structure Lecture#12: Binary Trees 3 (Chapter 5) U Kang Seoul National University

Heap: Complete binary tree with the heap property: Min-heap: All values less than child values. Max-heap: All values greater than child values.

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

Binary Trees

Binary Trees, Binary Search Trees

Chapter 20: Binary Trees

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

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

Bioinformatics Programming. EE, NCKU Tien-Hao Chang (Darby Chang)

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

Programming II (CS300)

Programming II (CS300)

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

Trees. Q: Why study trees? A: Many advance ADTs are implemented using tree-based data structures.

9. Heap : Priority Queue

Trees! Ellen Walker! CPSC 201 Data Structures! Hiram College!

Data Structures and Algorithms

TREES. Trees - Introduction

Heaps. Heaps Priority Queue Revisit HeapSort

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

DATA STRUCTURES AND ALGORITHMS. Hierarchical data structures: AVL tree, Bayer tree, Heap

Heaps. Heaps. A heap is a complete binary tree.

Binary Trees and Binary Search Trees

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs

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

ECE 242 Data Structures and Algorithms. Heaps I. Lecture 22. Prof. Eric Polizzi

COMP 103 RECAP-TODAY. Priority Queues and Heaps. Queues and Priority Queues 3 Queues: Oldest out first

CSE 214 Computer Science II Heaps and Priority Queues

CS350: Data Structures Heaps and Priority Queues

Data Structures Question Bank Multiple Choice

Programming II (CS300)

CH 8. HEAPS AND PRIORITY QUEUES

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text)

CH. 8 PRIORITY QUEUES AND HEAPS

Trees. CSE 373 Data Structures

INF2220: algorithms and data structures Series 1

Analysis of Algorithms

Algorithms and Data Structures

CMSC 341 Lecture 14: Priority Queues, Heaps

Trees, Binary Trees, and Binary Search Trees

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

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

CS24 Week 8 Lecture 1

Heapsort. Heap data structure

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

CHAPTER 5. Trees CHAPTER 5 1/70

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

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

Chapter 9. Priority Queue

Friday Four Square! 4:15PM, Outside Gates

Overview of Presentation. Heapsort. Heap Properties. What is Heap? Building a Heap. Two Basic Procedure on Heap

Trees. A tree is a directed graph with the property

Tree traversals and binary trees

Stores a collection of elements each with an associated key value

COMP : Trees. COMP20012 Trees 219

Trees & Tree-Based Data Structures. Part 4: Heaps. Definition. Example. Properties. Example Min-Heap. Definition

Todays Lecture. Assignment 2 deadline: You have 5 Calendar days to complete.

Data Structures and Algorithms

CSCI2100B Data Structures Heaps

CSI33 Data Structures

Binary heaps (chapters ) Leftist heaps

Definition of a Heap. Heaps. Priority Queues. Example. Implementation using a heap. Heap ADT

CSE 373 APRIL 17 TH TREE BALANCE AND AVL

Priority Queues. 1 Introduction. 2 Naïve Implementations. CSci 335 Software Design and Analysis III Chapter 6 Priority Queues. Prof.

Chapter 6 Heaps. Introduction. Heap Model. Heap Implementation

3. Priority Queues. ADT Stack : LIFO. ADT Queue : FIFO. ADT Priority Queue : pick the element with the lowest (or highest) priority.

Chapter 5. Binary Trees

Self-Balancing Search Trees. Chapter 11

Uses for Trees About Trees Binary Trees. Trees. Seth Long. January 31, 2010

March 20/2003 Jayakanth Srinivasan,

CMSC 341 Priority Queues & Heaps. Based on slides from previous iterations of this course

CSCI 136 Data Structures & Advanced Programming. Lecture 22 Fall 2018 Instructor: Bills

Binary Trees. Examples:

Topic: Heaps and priority queues

CMSC 341 Lecture 15 Leftist Heaps

Binary Trees. College of Computing & Information Technology King Abdulaziz University. CPCS-204 Data Structures I

Data Structure Chapter 5. Binary Trees

Priority queues. Priority queues. Priority queue operations

Properties of a heap (represented by an array A)

CSE100. Advanced Data Structures. Lecture 13. (Based on Paul Kube course materials)

Data Structure - Binary Tree 1 -

Priority Queues. Lecture15: Heaps. Priority Queue ADT. Sequence based Priority Queue

Data Structures and Algorithms for Engineers

Binary Trees. Height 1

Cosc 241 Programming and Problem Solving Lecture 21 (15/5/2017) Heaps

Heaps & Priority Queues. (Walls & Mirrors - Remainder of Chapter 11)

BM267 - Introduction to Data Structures

Trees (Part 1, Theoretical) CSE 2320 Algorithms and Data Structures University of Texas at Arlington

CSE 230 Intermediate Programming in C and C++ Binary Tree

Heap Model. specialized queue required heap (priority queue) provides at least

CE 221 Data Structures and Algorithms

8. Binary Search Tree

Principles of Computer Science

Algorithms in Systems Engineering ISE 172. Lecture 16. Dr. Ted Ralphs

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

CMSC 341 Lecture 15 Leftist Heaps

Data Structures Brett Bernstein

Data Structures Lesson 9

Data Structure. IBPS SO (IT- Officer) Exam 2017

Operations on Heap Tree The major operations required to be performed on a heap tree are Insertion, Deletion, and Merging.

Transcription:

Directed, Rooted Tree Binary Trees Chapter 5 CPTR 318 Every non-empty directed, rooted tree has A unique element called root One or more elements called leaves Every element except root has a unique parent All elements have zero or more children A leaf has no children A non-leaf has one or more children We will deal only with directed, rooted trees 1 2 Trees A tree with n 1 nodes contains n 1 edges Can you prove this? Every node except root has a parent An edge connects a node to its parent Terminology Path A sequence of nodes n 0, n 1, n 2,, n k such that n i is the parent of n i+1 for all 1 i k Path length The number of edges on the path; n 1 In a tree there is exactly one path from the root to a given node Node depth Depth of n i is the length of the path from the root to n i Node height Length of longest path to a leaf Tree height Depth of the deepest node + 1 Possible Implementation template <typename T> struct Node T data; std::list<node *> children; ; Binary Trees Each node may have 0, 1, or 2 children What is the minimum height of a binary tree with n nodes? What is the maximum height of a binary tree with n nodes? 1

Binary Search Tree Binary Tree Traversals For all nodes in the binary tree T: All the nodes in the left subtree of T s root are less than T s root node All the nodes in the right subtree of T s root are greater than T s root node template <typename T> struct Node T data; Node *left; Node *right; ; Preorder: node, preorder left subtree, preorder right subtree Inorder: inorder left subtree, node, inorder right subtree Postorder: postorder left subtree, postorder right subtree, node Easily expressed recursively Reconstruction from traversals Can you deduce the structure of a binary tree from one of its traversals? Use two traversals Balancing Problem Binary trees work best when balanced How can we keep a tree balanced? Priority Queues We would like to insert (enqueue) an element with a given priority We would like to serve (dequeue) the element with the highest priority Use a standard queue? What is the time to enqueue? O(1) What is the time to dequeue? O(n) Insertions cheap, deletions more expensive 11 12 2

Keep a sorted queue? Complete Binary Tree What is the time to enqueue? O(n) What is the time to dequeue? O(1) Insertions more expensive, deletions cheap A binary tree (not a binary search tree) Completely filled as much as possible, given its size Only possible incomplete level is the last level Last level is filled left to right 13 14 Easily mapped to an array Navigating the Array Version left_child(i) = 2i + 1 right_child(i) = 2i + 2 parent(i) = i 1 2 A B C D E F G H I J 0 1 2 3 4 5 6 7 8 9 10 11 12 A B C D E F G H I J 0 1 2 3 4 5 6 7 8 9 10 11 12 16 Navigating the Array Version Advantage of Array Representation? left_child(i) = 2i + 1 right_child(i) = 2i + 2 parent(i) = i 1 2 A B C D E F G H I J 0 1 2 3 4 5 6 7 8 9 10 11 12 Saves space no links required 17 18 3

Heap Order Property Smallest (or largest) element is at the root value(parent(i)) value(i), for all i root parent(root) is undefined Heap Implementation template <typename T, typename Comp> class Heap private: T* heap; // Pointer to the heap array int maxsize; // Maximum size of the heap int n; // Number of elements now in the heap // Methods omitted //... ; 19 22 23 24 25 4

Insertion (in book) heap[curr] = elem; // Start at end of heap swap(heap, curr, parent(curr)); Page 180 26 27 Insertion Insertion heap[curr] = elem; // Start at end of heap swap(heap, curr, parent(curr)); Page 180 swap(heap, curr, parent(curr)); heap[curr] = elem; // Place new element Page 180 28 Insertion Insertion swap(heap, curr, parent(curr)); heap[curr] = elem; // Place new element Page 180 heap[curr] = heap[parent(curr)]; heap[curr] = elem; // Place new element Page 180 5

Insertion (improved) Insertion Time complexity heap[curr] = heap[parent(curr)]; heap[curr] = elem; // Place new element Worst case O(log n) On average much better 2.607 comparisons O(1) 35 36 37 38 CPTR 314 6

39 CPTR 314 40 // Remove first value T removefirst() Assert (n > 0, "Heap is empty"); swap(heap, 0, --n); // Swap first with last element if ( n!= 0 ) siftdown(0); // Sift down new root element return heap[n]; // Return deleted value Page 181 Siftdown (in book) // Helper function to put element in its correct place void siftdown(int pos) while (!isleaf(pos)) // Stop if pos is a leaf int j = leftchild(pos), rc = rightchild(pos); if ((rc < n) && Comp::prior(heap[rc], heap[j])) j = rc; // Set j to greater child s value if (Comp::prior(heap[pos], heap[j])) return; // Done swap(heap, pos, j); pos = j; // Move down Page 180 Siftdown (improved) // Helper function to put element in its correct place void siftdown(int pos) T temp = heap[pos]; while (!isleaf(pos)) // Stop if pos is a leaf int j = leftchild(pos), rc = rightchild(pos); if ((rc < n) && Comp::prior(heap[rc], heap[j])) j = rc; // Set j to greater child s value if (Comp::prior(temp, heap[j])) break; // Done heap[pos] = heap[j]; pos = j; // Move down heap[pos] = temp; Time Complexity Worst case O(log n) Average case O(log n) 7

Decrease Key Build Heap If the value of an element in a min-heap decreases (or increases in a max-heap), the value may need to move up (or down) to maintain the heap property For example, circumstances may result in a lower priority job being elevated to a higher priority Several well-known graph algorithms make use of this operation decrease_key is worst case O(log n), but many times in practice an element usually moves only a small distance due to a small change in value Makes a heap out of an array of unordered elements Insert n elements Each insert is O(log n) worst case time, O(1) average time O(n log n) worst case, O(n) average case Huffman Trees Fixed-width character encoding vs. variablewidth character encoding 8