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

Similar documents
! 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

Binary Trees, Binary Search Trees

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

Heaps. A complete binary tree can be easily stored in an array - place the root in position 1 (for convenience)

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

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

Programming II (CS300)

Trees, Binary Trees, and Binary Search Trees

Chapter 20: Binary Trees

Data Structures in Java

Data Structures and Algorithms for Engineers

CSI33 Data Structures

TREES. Trees - Introduction

COMP : Trees. COMP20012 Trees 219

Data Structures. Giri Narasimhan Office: ECS 254A Phone: x-3748

CMSC 341 Lecture 10 Binary Search Trees

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

CE 221 Data Structures and Algorithms

4. Trees. 4.1 Preliminaries. 4.2 Binary trees. 4.3 Binary search trees. 4.4 AVL trees. 4.5 Splay trees. 4.6 B-trees. 4. Trees

Trees. A tree is a directed graph with the property

Trees. Trees. CSE 2011 Winter 2007

Why Do We Need Trees?

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

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

CSCI2100B Data Structures Trees

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

Recall: Properties of B-Trees

Programming II (CS300)

CMSC 341. Binary Search Trees CMSC 341 BST

Binary Trees

CSI33 Data Structures

Data Structures and Algorithms

Outline. Preliminaries. Binary Trees Binary Search Trees. What is Tree? Implementation of Trees using C++ Tree traversals and applications

CS350: Data Structures Heaps and Priority Queues

CE 221 Data Structures and Algorithms

CS302 - Data Structures using C++

Analysis of Algorithms

CS 234. Module 8. November 15, CS 234 Module 8 ADT Priority Queue 1 / 22

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

Binary Trees and Binary Search Trees

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

Binary Trees. Examples:

Figure 1: A complete binary tree.

Binary Heaps. COL 106 Shweta Agrawal and Amit Kumar

CSE 214 Computer Science II Heaps and Priority Queues

CMSC 341 Lecture 14: Priority Queues, Heaps

Binary Heaps. CSE 373 Data Structures Lecture 11

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

Programming II (CS300)

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

INF2220: algorithms and data structures Series 1

CMSC 341 Lecture 15 Leftist Heaps

March 20/2003 Jayakanth Srinivasan,

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

CMSC 341 Leftist Heaps

Binary Search Trees. See Section 11.1 of the text.

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

CMSC 341 Lecture 15 Leftist Heaps

CS 350 : Data Structures Binary Search Trees

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

Priority Queues (Heaps)

Data Structures. Giri Narasimhan Office: ECS 254A Phone: x-3748

CSCI2100B Data Structures Heaps

CS350: Data Structures Binary Search Trees

Data Structures Question Bank Multiple Choice

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

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

Course Review. Cpt S 223 Fall 2009

Priority Queues (Heaps)

CS211, LECTURE 20 SEARCH TREES ANNOUNCEMENTS:

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

8. Write an example for expression tree. [A/M 10] (A+B)*((C-D)/(E^F))

Trees. CSE 373 Data Structures

Chapter 5. Binary Trees

12 Abstract Data Types

Also, recursive methods are usually declared private, and require a public non-recursive method to initiate them.

CS102 Binary Search Trees

6-TREE. Tree: Directed Tree: A directed tree is an acyclic digraph which has one node called the root node

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

MIDTERM EXAMINATION Spring 2010 CS301- Data Structures

Readings. Priority Queue ADT. FindMin Problem. Priority Queues & Binary Heaps. List implementation of a Priority Queue

IX. Binary Trees (Chapter 10)

Heaps, Heap Sort, and Priority Queues.

BINARY HEAP cs2420 Introduction to Algorithms and Data Structures Spring 2015

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard

Exam Data structures DAT036/DAT037/DIT960

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

CS 231 Data Structures and Algorithms Fall Recursion and Binary Trees Lecture 21 October 24, Prof. Zadia Codabux

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

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

LECTURE 13 BINARY TREES

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

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

Principles of Computer Science

3137 Data Structures and Algorithms in C++

INF2220: algorithms and data structures Series 1

Stacks, Queues and Hierarchical Collections

COSC 2007 Data Structures II Final Exam. Part 1: multiple choice (1 mark each, total 30 marks, circle the correct answer)

Friday Four Square! 4:15PM, Outside Gates

Transcription:

Trees, Binary Search Trees, and Heaps CS 5301 Fall 2013 Jill Seaman Tree: non-recursive definition Tree: set of nodes and directed edges - root: one node is distinguished as the root - Every node (except root) has exactly exactly one edge coming into it. - Every node can have any number of edges going out of it (zero or more). Parent: source node of directed edge Child: terminal node of directed edge Gaddis ch. 20, Main + Savitch: ch. 10, 11.1-2 1 2 Tree: example Tree: recursive definition edges are directed down (source is higher) Tree: - is empty or - consists of a root node and zero or more nonempty subtrees, with an edge from the root to each subtree (a subtree is a Tree). D is the parent of H. Q is a child of J. Leaf: a node with no children (like H and P) Sibling: nodes with same parent (like K,L,M) 3 4

Tree terms Path: sequence of (directed) edges Length of path: number of edges on the path Depth of a node: length of path from root to that node. Height of a node: length of longest path from node to a leaf. 5 Tree traversal Tree traversal: operation that converts the values in a tree into a list - Often the list is output Pre-order traversal - Print the data from the root node - Do a pre-order traversal on first subtree - Do a pre-order traversal on second subtree... - Do a preorder traversal on last subtree This is recursive. What s the base case? 6 Preorder traversal: Expression Tree print node value, process left tree, then right Postorder traversal: Expression Tree process left tree, then right, then node + + a * b c * + * d e f g prefix notation (for arithmetic expressions) 7 a b c * + d e * f + g * + postfix notation (for arithmetic expressions) 8

Inorder traversal: Expression Tree if each node has 0 to 2 children, you can do inorder traversal process left tree, print node value, then process right tree a + b * c + d * e + f * g infix notation (for arithmetic expressions) 9 Binary Trees Binary Tree: a tree in which no node can have more than two children. height: shortest: log2(n) tallest: n n is the number of nodes in the tree. 10 Binary Trees: implementation Binary Search Trees Structure with a data value, and a pointer to the left subtree and another to the right subtree. struct TreeNode { <type> data; // the data BinaryNode *left; // left subtree BinaryNode *right; // right subtree }; Like a linked list, but two next pointers. This structure can be used to represent any binary tree. 11 A special kind of binary tree A data structure used for efficient searching, insertion, and deletion. Binary Search Tree property: For every node X in the tree: - All the values in the left subtree are smaller than the value at X. - All the values in the right subtree are larger than the value at X. Not all binary trees are binary search trees 12

Binary Search Trees Binary Search Trees An inorder traversal of a BST shows the values in sorted order A binary search tree Not a binary search tree 13 Inorder traversal: 2 3 4 6 7 9 13 15 17 18 20 14 Binary Search Trees: operations BST: find(x) insert(x) remove(x) (or delete) isempty() (returns bool) find(x) (returns bool) findmin() (returns ItemType) findmax() (returns ItemType) 15 Recursive Algorithm: if we are searching for 15 we are done. If we are searching for a key < 15, then we should search in the left subtree. If we are searching for a key > 15, then we should search in the right subtree. 16

BST: find(x) BST: find(x) Pseudocode Example: search for 9 compare 9 to 15, go left compare 9 to 6, go right compare 9 to 7 go right compare 9 to 13 go left compare 9 to 9: found 17 Recursive bool find (ItemType x, TreeNode t) { if (isempty(t)) Base case return false if (x < value(t)) return find (x, left(t)) if (x > value(t)) return find (x, right(t)) } return true // x == value(t) 18 BST: findmin() BST: insert(x) Smallest element is found by always taking the left branch. Pseudocode Recursive Tree must not be empty ItemType findmin (TreeNode t) { assert (isempty(t)) if (isempty(left(t))) return value(t) return findmin (left(t)) } 19 Algorithm is similar to find(x) If x is found, do nothing (no duplicates in tree) If x is not found, add a new node with x in place of the last empty subtree that was searched. Inserting 13: 20

Pseudocode Recursive BST: insert(x) bool insert (ItemType x, TreeNode t) { if (isempty(t)) make t s parent point to new TreeNode(x) else if (x < value(t)) insert (x, left(t)) else if (x > value(t)) insert (x, right(t)) //else x == value(t), do nothing, no duplicates } 21 Append x to the end of a singly linked list: - Pass the node pointer by reference - Recursive Linked List example: void List::append (double x) { Public function append(x, head); } void List::append (double x, Node *& p) { Private recursive function if (p == NULL) { p = new Node(); p->data = x; p->next = NULL; } else append (x, p->next); 22 } BST: remove(x) BST: remove(x) Algorithm is starts with finding(x) Case 1: Node is a leaf If x is not found, do nothing If x is not found, remove node carefully. - Must remain a binary search tree (smallers on left, biggers on right). - Can be removed without violating BST property Case 2: Node has one child - Make parent pointer bypass the Node and point to child Does not matter if the child is the left or right child of deleted node 23 24

BST: remove(x) Binary heap data structure Case 3: Node has 2 children - Replace it with the minimum value in the right subtree - Remove minimum in right: will be a leaf (case 1), or have only a right subtree (case 2) --cannot have left subtree, or it s not the minimum remove(2): replace it with the minimum of its right subtree (3) and delete that node. A binary heap is a special kind of binary tree - has a restricted structure (must be complete) - has an ordering property (parent value is smaller than child values) - NOT a Binary Search Tree Used in the following applications - Priority queue implementation: supports enqueue and deletemin operations in O(log N) - Heap sort: another O(N log N) sorting algorithm. 25 26 Binary Heap: structure property Complete Binary Trees Complete binary tree: a tree that is completely filled - every level except the last is completely filled. - the bottom level is filled left to right (the leaves are as far left as possible). A complete binary tree can be easily stored in an array - place the root in position 1 (for convenience) 27 28

Complete Binary Trees Properties In the array representation: - put root at location 1 - use an int variable (size) to store number of nodes - for a node at position i: - left child at position 2i (if 2i <= size, else i is leaf) - right child at position 2i+1 (if 2i+1 <= size, else i is leaf) - parent is in position floor(i/2) (or use integer division) Binary Heap: ordering property In a heap, if X is a parent of Y, value(x) is less than or equal to value(y). - the minimum value of the heap is always at the root. 29 30 Heap: insert(x) Heap: insert(x) First: add a node to tree. - must be placed at next available location, size+1, in order to maintain a complete tree. Next: maintain the ordering property: - if x is greater than its parent: done - else swap with parent, repeat Called percolate up or reheap up preserves ordering property 31 32

Heap: deletemin() Heap: deletemin() Minimum is at the root, removing it leaves a hole. - The last element in the tree must be relocated. First: move last element up to the root Next: maintain the ordering property, start with root: - if both children are greater than the parent: done - otherwise, swap the smaller of the two children with the parent, repeat Called percolate down or reheap down preserves ordering property O(log n) 33 34