Announcements. Midterm exam 2, Thursday, May 18. Today s topic: Binary trees (Ch. 8) Next topic: Priority queues and heaps. Break around 11:45am

Size: px
Start display at page:

Download "Announcements. Midterm exam 2, Thursday, May 18. Today s topic: Binary trees (Ch. 8) Next topic: Priority queues and heaps. Break around 11:45am"

Transcription

1 Announcements Midterm exam 2, Thursday, May 18 Closed book/notes but one sheet of paper allowed Covers up to stacks and queues Today s topic: Binary trees (Ch. 8) Next topic: Priority queues and heaps Break around 11:45am 1

2 Hierarchical data structures So far, we ve been studying linear structures An array s memory layout and a linked list s link pointers define an underlying linear order Now, hierarchical or branching structures Trees! 2

3 Motivation for trees For arrays: the insert operation is Θ(n) searching is Θ(n) or Θ(log n) For linked lists: the insert operation is Θ(1) (but Θ(n) to find the right spot) searching is Θ(n) (even if the list is sorted) Is there a data structure with Θ(log n) performance for all three operations: insert, remove, and search? Try tree! Reminder: n vs. log n n = 1,048,576 log 2 n = 20 3

4 Tree overview A tree is a collection of nodes with the following properties: each node contains or references data (the payload). If the collection is not empty, there is one node called the root which is the top of a hierarchy. All other nodes are connected to the root node with a unique path (implies nodes only have 1 parent node). Some examples: Family trees Organization charts Directory hierarchies Parse trees in a compiler a = (b + c) * d + d a = * b c 4

5 Trees tree: A directed, acyclic structure of linked nodes. directed : Has one-way links between nodes. acyclic : No path wraps back around to the same node twice. binary tree: One where each node has at most two children. A binary tree is either: empty, or a root node that contains: data, a left subtree, and 5 root 7 3 a right subtree Recursive definition of a recursive data structure! 5

6 Terminology node: an object containing a data value and left/right children root: topmost node of a tree leaf: a node that has no children internal node; neither the root nor a leaf parent: child: sibling: a node with a common parent root

7 Terminology (cont.) subtree: the tree of nodes reachable to the left/right from the current node height: length of the longest path from the root to any node (single element tree is height of 0) level or depth: length of the path from a root to a given node full tree: one where every internal node has 2 children Level 0 Level 1 height = 2 5 root 7 3 Level

8 A tree node for integers A basic tree node object stores data and refers to left/right left data right 42 Multiple nodes can be linked together into a larger tree left data right 42 left data right left data right left data right 86 8

9 Recursive data structures ---> recursive functions Number of nodes (size) in binary tree t: If t is empty size(t) = 0 else size(t) = 1 + size(leftsubtree(t)) + size(rightsubtree(t)) The height of binary tree t: If t is empty height(t) = -1 // want the height of a single node tree to be 0 else height(t) = 1 + max(height(leftsubtree(t)), height(rightsubtree(t))) 9

10 Full and complete trees A binary tree is full if each node is either a leaf node or a node that has 2 children. A perfect binary tree is a full binary tree with all leaf nodes at the same level. A binary tree T is complete if all levels except possibly the last are completely full, and the last level has all its nodes to the left side. Similar definitions but logically independent. 10

11 11

12 Max number of nodes The number of nodes in a perfect binary tree with h levels (0 through h)? At level h, there are 2 h nodes, so maxnodes = h = 2 h

13 Min and max number of levels, h What is the minimum number of levels of a full binary tree with n nodes? Let s use results from previous slide. n = 2 h 1 h min = log 2 (n+1) What is the maximum number of levels of a binary tree? This is a degenerate case... essentially a linked list! So: h max = n 13

14 Tree traversal Often we traverse a tree for various operations Three simple approaches: pre-order in-order post-order These are linear-time, depth-first traversals 14

15 Example: traversals A B C D E F G As you traverse depth-first, left-to-right, Preorder: print the element the first time you encounter it including null pointers A B D E C F G Inorder: print the element the second time you encounter it D B E A F C G Postorder: print the element the last time you encounter it D E B F G C A 15

16 Pre-order traversal Pre-order: root-left-right preorder(t) { if (t is not empty) { access the root element of t; preorder(leftsubtree(t)); preorder(rightsubtree(t)); 16

17 In-order traversal In-order: left-root-right inorder(t) { if (t is not empty) { inorder(leftsubtree(t)); access root element of t; inorder(rightsubtree(t)); 17

18 Post-order traversal Post-order: left-right root postorder(t) { if (t is not empty) { postorder(leftsubtree(t)); postorder(rightsubtree(t)); access the root element of t; 18

19 Tree traversals Level-order traversal Example of breadth-first traversal Pre-order, in-order, post-order traversals Example of depth-first traversal For a general tree (not a binary) In-order traversal not well defined Can do level-order, pre-order, post-order 19

20 Level-order traversal Begins at root, visits nodes one level at a time: 1, 2, 3,..., 10, 11 20

21 Example implementation: levelorder traversal You can see an implementation (levelorderprint) in BST.java that we will see later (see after you study the BST implementation first) Implementation uses a queue! 21

22 Binary Search Trees (BSTs) A BST t is a binary tree such that either t is empty, or 1. each element in leftsubtree(t) is less than root(t), and 2. each element in rightsubtree(t) is greater than root(t), and 3. both leftsubtree(t) and rightsubtree(t) are BSTs

23 Use of BSTs A tree as a set, e.g., java.util.treeset Spell checker Tree sort... A tree as a map, e.g., java.util.treemap Dictionary Address book... 23

24 Valid BST? Which of the trees shown are legal binary search trees? g m q b k x e

25 Searching a BST Describe an algorithm for searching the tree below for 31. Then search for value 6. root What is the maximum number of nodes you would need to examine to perform any search?

26 Recursive search pseudocode searchtreerec(node, key) { if (node is empty) return null if (key < node s key) return searchtreerec(node s left child, key) else if (key > node s key) return searchtreerec(node s right child, key) else return node 26

27 Iterative search pseudocode searchtree(node, key) { while (node is not empty) { if (key < node s key) node = node s left child else if (key > node s key) node = node s right child else return node 27

28 Intuitive search performance of BST For now, let s assume the binary tree splits in half at every node. Every time we descend to a child node we cut the number of remaining nodes to be searched in half. Sounds familiar? Θ(log n)! 28

29 Balanced? A balanced tree 2 An unbalanced tree

30 BSTs Performance: Search: Θ(log n) Insert: Θ(log n) Delete: Θ(log n)... on average... worst case is Θ(n) but this is rare there are strategies for avoiding the worst case 30

31 BST comparison Operation Theta Comparison (Average Case) BST Array-based List Linked List retrieve Θ(logN) Θ(logN) (?) Θ(N) insert Θ(logN) Θ(N) Θ(N) delete Θ(logN) Θ(N) Θ(N) 31

32 Some properties of BSTs The minimum node in a BST (or any of its subtrees) is the left-most node. To find the minimum node, we traverse down the left subtree until we find a node with an empty left child reference. The maximum node in a BST (or any of its subtrees) is the right-most node. To find the maximum node, we traverse down the right subtree until we find a node with an empty right child reference. An inorder traversal generates a list of the nodes in sorted order. This is the idea behind Tree Sort: put a random input sequence into a BST and then use an inorder traversal when you want the sorted sequence in a list. See successor method in BST.java (which is used in iterator) 32

33 Minimum and maximum value no left child so, minimum node no right child so, maximum node

34 findmin, iterative // returns the minimum value from this BST public int findmin() { if (root == null) { throw new NoSuchElementException(); return findminnode(root).element; private Node findminnode(node nptr) { if (nptr == null) return null; while (nptr.left!= null) { nptr = nptr.left; return nptr; root

35 findmin, recursive // returns the minimum value from this BST. public int findmin() { if (root == null) { throw new NoSuchElementException(); return findmin(root); private int findmin(node nptr) { if (nptr.left == null) { return nptr.element; else { return findmin(nptr.left); 29 root

36 Adding to a BST Add 14, and 3 in that order If the tree is empty, where should a new value be added? What is the general algorithm? Is the resulting tree unique when you add an element? 36

37 Adding an entry into a BST Add new entry as a leaf node. Descend down the tree checking each node s left or right subtrees to see if the new node can be added there. If the tree already has the element, don t add a duplicate. Otherwise, continue. When an empty left or right reference is found, create a node and attach it there. 37

38 Example add method Let s look at an iterative add() method. See BST.java, UseBST.java, Student.java Let s try a recursive add() method 38

39 An incorrect solution // Adds the given value to this BST in sorted order. public void addrec(int value) { add(root, value); private void add(node nptr, int value) { if (nptr == null) { nptr = new Node(value); else if (nptr.element > value) { add(nptr.left, value); else if (nptr.element < value) { add(nptr.right, value); // else nptr.element == value; // a duplicate (don't add) Why doesn't this solution work? What happens if you are adding a node to an empty tree! root

40 A recursive add public void addrec(int val) { if (root == null) { root = new Node(val, null); else { addrec(root, val); private static void addrec(node nptr, int val) { if (val > nptr.element) { if (nptr.right == null) nptr.right = new Node(val, nptr); // 2nd is parent else addrec(nptr.right, val); else if (val < nptr.element) { if (nptr.left == null) nptr.left = new Node(val, nptr); else addrec(nptr.left, val); 40

41 Another recursive add // Adds the given value to this BST in sorted order. public void add(int value) { root = add(root, value); private IntTreeNode add(node nptr, int value) { if (nptr == null) { nptr = new Node(value); else if (nptr.element > value) { nptr.left = add(nptr.left, value); else if (nptr.element < value) { nptr.right = add(nptr.right, value); // else a duplicate root 55 return nptr;

42 Removing a node First we must find the node to be deleted Once we ve found the node, there are three cases to consider. Case 1: The found node is a leaf node. Simplest case. Simply set the appropriate link in the parent to null. (Yes, each node has a parent reference!) Case 2: The found node is an interior node with 1 child Set the appropriate link in the parent to the found node s child. 42

43 Cases 1 and 2 for removal a leaf: replace with null a node with a left child only: replace with left child a node with a right child only: replace with right child root root root root t1.remove(55); t1.remove(-3); t1.remove(29); 43

44 Removing a node (cont.) Case 3: The found node is a node with 2 children. One approach is to find a successor node and replace the found node with it. The successor node is the node that would immediately follow the found node if all the nodes in the tree were laid out in a sorted linear manner (the next node from the found node in inorder traversal order). Where is this node? It s the minimum node in the right subtree i.e., the left-most node in the right subtree. Replace the found node s value with the successor node s value. Remove the successor node from the right subtree. Is the resulting tree unique when you remove a node? 44

45 Case 3 for removal a node with both children: replace it with min from right subtree root 55 t1.remove(55); root

46 Example remove method See BST.java, UseBST.java, Student.java 46

47 Recursive remove // Removes the given value from this BST, if it exists. public void remove(int value) { root = remove(root, value); private Node remove(node root, int value) { if (root == null) { return null; else if (root.element > value) { root.left = remove(root.left, value); else if (root.element < value) { root.right = remove(root.right, value); else { // root.element == value; remove this node if (root.right == null) { return root.left; // no R child; replace w/ L else if (root.left == null) { return root.right; // no L child; replace w/ R else { // both children; replace w/ min from R root.element = getmin(root.right); root.right = remove(root.right, root.element); return root; 47

48 Iterator Initialize it to point to the smallest element in the tree. Next() returns the next element in the inorder order in succession using the successor function. See BST.java 48

49 Tree shape We ve seen that the performance of search, add, and remove is dependent on the shape of the tree... specifically the tree s height. A balanced tree has a minimal height which gives the average case performance of Θ(log n). However, the shape of the tree is dependent on the order which entries are added. What kind of sequences are the worst balance-wise? 49

50 Tree balancing How to get a balanced tree? One approach: Sort the array of elements to be added to the tree Add the middle element of the input array, then the middle elements of the 2 halves, then the middle elements of the 4 fourths, etc. Problem: only works if we are given the input array upfront. In many cases the elements arrive asynchronously. What if we could balance the tree on the fly as elements are added and removed? 50

51 Self-balancing trees Two well-known algorithms for maintaining balance in a tree are: AVL Trees older technique that serves as a model for more modern techniques. Created by Russian mathematicians Georgii Adelson-Velskii and Evgenii Landis in Red Black Trees popular and efficient technique used in the Java Collections Framework. Developed in its modern form by Leonidas Guibas and Robert Sedgewick in Both algorithms utilize Tree Rotations. 51

52 Overview of AVL algorithm The AVL algorithm keeps track of how balanced a tree is by using a balance factor for each node. A node s balance factor is the height of the right subtree minus the height of the left subtree. A tree is unbalanced when the absolute value of the root s balance factor is greater than 1. When a new node is added that unbalances the tree, balance can be restored by performing either a single rotation or a double rotation. 52

53 Tree rotations See 53

54 Trees in Java Collections Framework The TreeSet class provides an implementation of the Set interface that utilizes a tree for storage. Objects are stored in sorted, ascending order. This is a balanced tree implementation. Note: as a set duplicates are not allowed. The TreeMap class provides storage and sorting of key-value pairs (see Map.Entry<K,V>). Entries are sorted by keys. Utilizes a red-black tree for storage. Note: keys as a set duplicate keys are not allowed although duplicate values are allowed. 54

55 What next? Study BST.java, UseBST.java, Student.java first Then: Priority queues and binary heaps next 55

Hierarchical data structures. Announcements. Motivation for trees. Tree overview

Hierarchical data structures. Announcements. Motivation for trees. Tree overview Announcements Midterm exam 2, Thursday, May 18 Closed book/notes but one sheet of paper allowed Covers up to stacks and queues Today s topic: Binary trees (Ch. 8) Next topic: Priority queues and heaps

More information

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

Trees. (Trees) Data Structures and Programming Spring / 28 Trees (Trees) Data Structures and Programming Spring 2018 1 / 28 Trees A tree is a collection of nodes, which can be empty (recursive definition) If not empty, a tree consists of a distinguished node r

More information

Advanced Tree Data Structures

Advanced Tree Data Structures Advanced Tree Data Structures Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park Binary trees Traversal order Balance Rotation Multi-way trees Search Insert Overview

More information

9/29/2016. Chapter 4 Trees. Introduction. Terminology. Terminology. Terminology. Terminology

9/29/2016. Chapter 4 Trees. Introduction. Terminology. Terminology. Terminology. Terminology Introduction Chapter 4 Trees for large input, even linear access time may be prohibitive we need data structures that exhibit average running times closer to O(log N) binary search tree 2 Terminology recursive

More information

Introduction. for large input, even access time may be prohibitive we need data structures that exhibit times closer to O(log N) binary search tree

Introduction. for large input, even access time may be prohibitive we need data structures that exhibit times closer to O(log N) binary search tree Chapter 4 Trees 2 Introduction for large input, even access time may be prohibitive we need data structures that exhibit running times closer to O(log N) binary search tree 3 Terminology recursive definition

More information

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

DATA STRUCTURES AND ALGORITHMS. Hierarchical data structures: AVL tree, Bayer tree, Heap DATA STRUCTURES AND ALGORITHMS Hierarchical data structures: AVL tree, Bayer tree, Heap Summary of the previous lecture TREE is hierarchical (non linear) data structure Binary trees Definitions Full tree,

More information

Lecture 13: AVL Trees and Binary Heaps

Lecture 13: AVL Trees and Binary Heaps Data Structures Brett Bernstein Lecture 13: AVL Trees and Binary Heaps Review Exercises 1. ( ) Interview question: Given an array show how to shue it randomly so that any possible reordering is equally

More information

TREES. Trees - Introduction

TREES. Trees - Introduction TREES Chapter 6 Trees - Introduction All previous data organizations we've studied are linear each element can have only one predecessor and successor Accessing all elements in a linear sequence is O(n)

More information

Binary Trees, Binary Search Trees

Binary Trees, Binary Search Trees Binary Trees, Binary Search Trees Trees Linear access time of linked lists is prohibitive Does there exist any simple data structure for which the running time of most operations (search, insert, delete)

More information

Why Do We Need Trees?

Why Do We Need Trees? CSE 373 Lecture 6: Trees Today s agenda: Trees: Definition and terminology Traversing trees Binary search trees Inserting into and deleting from trees Covered in Chapter 4 of the text Why Do We Need Trees?

More information

Binary Trees

Binary Trees Binary Trees 4-7-2005 Opening Discussion What did we talk about last class? Do you have any code to show? Do you have any questions about the assignment? What is a Tree? You are all familiar with what

More information

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

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text) Lec 17 April 8 Topics: binary Trees expression trees Binary Search Trees (Chapter 5 of text) Trees Linear access time of linked lists is prohibitive Heap can t support search in O(log N) time. (takes O(N)

More information

Algorithms. AVL Tree

Algorithms. AVL Tree Algorithms AVL Tree Balanced binary tree The disadvantage of a binary search tree is that its height can be as large as N-1 This means that the time needed to perform insertion and deletion and many other

More information

Building Java Programs

Building Java Programs Building Java Programs Binary Trees reading: 17.1 17.3 2 Trees in computer science TreeMap and TreeSet implementations folders/files on a computer family genealogy; organizational charts AI: decision trees

More information

Analysis of Algorithms

Analysis of Algorithms Analysis of Algorithms Trees-I Prof. Muhammad Saeed Tree Representation.. Analysis Of Algorithms 2 .. Tree Representation Analysis Of Algorithms 3 Nomenclature Nodes (13) Size (13) Degree of a node Depth

More information

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

CISC 235 Topic 3. General Trees, Binary Trees, Binary Search Trees CISC 235 Topic 3 General Trees, Binary Trees, Binary Search Trees Outline General Trees Terminology, Representation, Properties Binary Trees Representations, Properties, Traversals Recursive Algorithms

More information

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

Discussion 2C Notes (Week 8, February 25) TA: Brian Choi Section Webpage: Discussion 2C Notes (Week 8, February 25) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs32 Trees Definitions Yet another data structure -- trees. Just like a linked

More information

CSCI2100B Data Structures Trees

CSCI2100B Data Structures Trees CSCI2100B Data Structures Trees Irwin King king@cse.cuhk.edu.hk http://www.cse.cuhk.edu.hk/~king Department of Computer Science & Engineering The Chinese University of Hong Kong Introduction General Tree

More information

Algorithms. Deleting from Red-Black Trees B-Trees

Algorithms. Deleting from Red-Black Trees B-Trees Algorithms Deleting from Red-Black Trees B-Trees Recall the rules for BST deletion 1. If vertex to be deleted is a leaf, just delete it. 2. If vertex to be deleted has just one child, replace it with that

More information

Module 4: Index Structures Lecture 13: Index structure. The Lecture Contains: Index structure. Binary search tree (BST) B-tree. B+-tree.

Module 4: Index Structures Lecture 13: Index structure. The Lecture Contains: Index structure. Binary search tree (BST) B-tree. B+-tree. The Lecture Contains: Index structure Binary search tree (BST) B-tree B+-tree Order file:///c /Documents%20and%20Settings/iitkrana1/My%20Documents/Google%20Talk%20Received%20Files/ist_data/lecture13/13_1.htm[6/14/2012

More information

COMP 250. Lecture 22. binary search trees. Oct. 30, 2017

COMP 250. Lecture 22. binary search trees. Oct. 30, 2017 COMP 250 Lecture 22 binary search trees Oct. 30, 2017 1 (binary search) tree binary (search tree) 2 class BSTNode< K >{ K BSTNode< K > BSTNode< K > : } key; leftchild; rightchild; The keys are comparable

More information

Trees. Eric McCreath

Trees. Eric McCreath Trees Eric McCreath 2 Overview In this lecture we will explore: general trees, binary trees, binary search trees, and AVL and B-Trees. 3 Trees Trees are recursive data structures. They are useful for:

More information

CSE 143 Lecture 19. Binary Trees. read slides created by Marty Stepp

CSE 143 Lecture 19. Binary Trees. read slides created by Marty Stepp CSE 143 Lecture 19 Binary Trees read 17.1-17.2 slides created by Marty Stepp http://www.cs.washington.edu/143/ Trees tree: A directed, acyclic structure of linked nodes. directed : Has one-way links between

More information

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

CMSC 341 Priority Queues & Heaps. Based on slides from previous iterations of this course CMSC 341 Priority Queues & Heaps Based on slides from previous iterations of this course Today s Topics Priority Queues Abstract Data Type Implementations of Priority Queues: Lists BSTs Heaps Heaps Properties

More information

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

CS 231 Data Structures and Algorithms Fall Recursion and Binary Trees Lecture 21 October 24, Prof. Zadia Codabux CS 231 Data Structures and Algorithms Fall 2018 Recursion and Binary Trees Lecture 21 October 24, 2018 Prof. Zadia Codabux 1 Agenda ArrayQueue.java Recursion Binary Tree Terminologies Traversal 2 Administrative

More information

Trees. CSE 373 Data Structures

Trees. CSE 373 Data Structures Trees CSE 373 Data Structures Readings Reading Chapter 7 Trees 2 Why Do We Need Trees? Lists, Stacks, and Queues are linear relationships Information often contains hierarchical relationships File directories

More information

Data Structures Question Bank Multiple Choice

Data Structures Question Bank Multiple Choice Section 1. Fundamentals: Complexity, Algorthm Analysis 1. An algorithm solves A single problem or function Multiple problems or functions Has a single programming language implementation 2. A solution

More information

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

Tree Structures. A hierarchical data structure whose point of entry is the root node Binary Trees 1 Tree Structures A tree is A hierarchical data structure whose point of entry is the root node This structure can be partitioned into disjoint subsets These subsets are themselves trees and

More information

COMP : Trees. COMP20012 Trees 219

COMP : Trees. COMP20012 Trees 219 COMP20012 3: Trees COMP20012 Trees 219 Trees Seen lots of examples. Parse Trees Decision Trees Search Trees Family Trees Hierarchical Structures Management Directories COMP20012 Trees 220 Trees have natural

More information

Trees : Part 1. Section 4.1. Theory and Terminology. A Tree? A Tree? Theory and Terminology. Theory and Terminology

Trees : Part 1. Section 4.1. Theory and Terminology. A Tree? A Tree? Theory and Terminology. Theory and Terminology Trees : Part Section. () (2) Preorder, Postorder and Levelorder Traversals Definition: A tree is a connected graph with no cycles Consequences: Between any two vertices, there is exactly one unique path

More information

Cpt S 122 Data Structures. Data Structures Trees

Cpt S 122 Data Structures. Data Structures Trees Cpt S 122 Data Structures Data Structures Trees Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Motivation Trees are one of the most important and extensively

More information

Binary Trees. Height 1

Binary Trees. Height 1 Binary Trees Definitions A tree is a finite set of one or more nodes that shows parent-child relationship such that There is a special node called root Remaining nodes are portioned into subsets T1,T2,T3.

More information

CMPE 160: Introduction to Object Oriented Programming

CMPE 160: Introduction to Object Oriented Programming CMPE 6: Introduction to Object Oriented Programming General Tree Concepts Binary Trees Trees Definitions Representation Binary trees Traversals Expression trees These are the slides of the textbook by

More information

3137 Data Structures and Algorithms in C++

3137 Data Structures and Algorithms in C++ 3137 Data Structures and Algorithms in C++ Lecture 4 July 17 2006 Shlomo Hershkop 1 Announcements please make sure to keep up with the course, it is sometimes fast paced for extra office hours, please

More information

Unit III - Tree TREES

Unit III - Tree TREES TREES Unit III - Tree Consider a scenario where you are required to represent the directory structure of your operating system. The directory structure contains various folders and files. A folder may

More information

Balanced Binary Search Trees

Balanced Binary Search Trees Balanced Binary Search Trees Pedro Ribeiro DCC/FCUP 2017/2018 Pedro Ribeiro (DCC/FCUP) Balanced Binary Search Trees 2017/2018 1 / 48 Motivation Let S be a set of comparable objects/items: Let a and b be

More information

Binary Trees and Huffman Encoding Binary Search Trees

Binary Trees and Huffman Encoding Binary Search Trees Binary Trees and Huffman Encoding Binary Search Trees Computer Science E-22 Harvard Extension School David G. Sullivan, Ph.D. Motivation: Maintaining a Sorted Collection of Data A data dictionary is a

More information

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

a graph is a data structure made up of nodes in graph theory the links are normally called edges 1 Trees Graphs a graph is a data structure made up of nodes each node stores data each node has links to zero or more nodes in graph theory the links are normally called edges graphs occur frequently in

More information

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

Outline. Preliminaries. Binary Trees Binary Search Trees. What is Tree? Implementation of Trees using C++ Tree traversals and applications Trees 1 Outline Preliminaries What is Tree? Implementation of Trees using C++ Tree traversals and applications Binary Trees Binary Search Trees Structure and operations Analysis 2 What is a Tree? A tree

More information

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

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs Computational Optimization ISE 407 Lecture 16 Dr. Ted Ralphs ISE 407 Lecture 16 1 References for Today s Lecture Required reading Sections 6.5-6.7 References CLRS Chapter 22 R. Sedgewick, Algorithms in

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms CS245-2017S-06 Binary Search Trees David Galles Department of Computer Science University of San Francisco 06-0: Ordered List ADT Operations: Insert an element in the list

More information

csci 210: Data Structures Trees

csci 210: Data Structures Trees csci 210: Data Structures Trees 1 Summary Topics general trees, definitions and properties interface and implementation tree traversal algorithms depth and height pre-order traversal post-order traversal

More information

CS102 Binary Search Trees

CS102 Binary Search Trees CS102 Binary Search Trees Prof Tejada 1 To speed up insertion, removal and search, modify the idea of a Binary Tree to create a Binary Search Tree (BST) Binary Search Trees Binary Search Trees have one

More information

Lecture 26. Introduction to Trees. Trees

Lecture 26. Introduction to Trees. Trees Lecture 26 Introduction to Trees Trees Trees are the name given to a versatile group of data structures. They can be used to implement a number of abstract interfaces including the List, but those applications

More information

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

Advanced Java Concepts Unit 5: Trees. Notes and Exercises Advanced Java Concepts Unit 5: Trees. Notes and Exercises A Tree is a data structure like the figure shown below. We don t usually care about unordered trees but that s where we ll start. Later we will

More information

Lecture 23: Binary Search Trees

Lecture 23: Binary Search Trees Lecture 23: Binary Search Trees CS 62 Fall 2017 Kim Bruce & Alexandra Papoutsaki 1 BST A binary tree is a binary search tree iff it is empty or if the value of every node is both greater than or equal

More information

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

Tree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example. 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

More information

Trees. A tree is a directed graph with the property

Trees. A tree is a directed graph with the property 2: Trees Trees A tree is a directed graph with the property There is one node (the root) from which all other nodes can be reached by exactly one path. Seen lots of examples. Parse Trees Decision Trees

More information

CMSC 341 Lecture 14: Priority Queues, Heaps

CMSC 341 Lecture 14: Priority Queues, Heaps CMSC 341 Lecture 14: Priority Queues, Heaps Prof. John Park Based on slides from previous iterations of this course Today s Topics Priority Queues Abstract Data Type Implementations of Priority Queues:

More information

BINARY SEARCH TREES cs2420 Introduction to Algorithms and Data Structures Spring 2015

BINARY SEARCH TREES cs2420 Introduction to Algorithms and Data Structures Spring 2015 BINARY SEARCH TREES cs2420 Introduction to Algorithms and Data Structures Spring 2015 1 administrivia 2 -assignment 7 due tonight at midnight -asking for regrades through assignment 5 and midterm must

More information

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

Uses for Trees About Trees Binary Trees. Trees. Seth Long. January 31, 2010 Uses for About Binary January 31, 2010 Uses for About Binary Uses for Uses for About Basic Idea Implementing Binary Example: Expression Binary Search Uses for Uses for About Binary Uses for Storage Binary

More information

Principles of Computer Science

Principles of Computer Science Principles of Computer Science Binary Trees 08/11/2013 CSCI 2010 - Binary Trees - F.Z. Qureshi 1 Today s Topics Extending LinkedList with Fast Search Sorted Binary Trees Tree Concepts Traversals of a Binary

More information

Algorithms and Data Structures

Algorithms and Data Structures Lesson 3: trees and visits Luciano Bononi http://www.cs.unibo.it/~bononi/ (slide credits: these slides are a revised version of slides created by Dr. Gabriele D Angelo) International

More information

Outline. Binary Tree

Outline. Binary Tree Outline Computer Science Mike Jacobson Department of Computer Science University of Calgary Lectures #8 9 The Dictionary ADT 2 Binary Trees s Relationship Between Size and Height Finding an Element with

More information

Data Structures and Algorithms for Engineers

Data Structures and Algorithms for Engineers 04-630 Data Structures and Algorithms for Engineers David Vernon Carnegie Mellon University Africa vernon@cmu.edu www.vernon.eu Data Structures and Algorithms for Engineers 1 Carnegie Mellon University

More information

CSE 373 OCTOBER 11 TH TRAVERSALS AND AVL

CSE 373 OCTOBER 11 TH TRAVERSALS AND AVL CSE 373 OCTOBER 11 TH TRAVERSALS AND AVL MINUTIAE Feedback for P1p1 should have gone out before class Grades on canvas tonight Emails went to the student who submitted the assignment If you did not receive

More information

CS24 Week 8 Lecture 1

CS24 Week 8 Lecture 1 CS24 Week 8 Lecture 1 Kyle Dewey Overview Tree terminology Tree traversals Implementation (if time) Terminology Node The most basic component of a tree - the squares Edge The connections between nodes

More information

Analysis of Algorithms

Analysis of Algorithms Analysis of Algorithms Concept Exam Code: 16 All questions are weighted equally. Assume worst case behavior and sufficiently large input sizes unless otherwise specified. Strong induction Consider this

More information

CISC 235: Topic 4. Balanced Binary Search Trees

CISC 235: Topic 4. Balanced Binary Search Trees CISC 235: Topic 4 Balanced Binary Search Trees Outline Rationale and definitions Rotations AVL Trees, Red-Black, and AA-Trees Algorithms for searching, insertion, and deletion Analysis of complexity CISC

More information

Search Trees. The term refers to a family of implementations, that may have different properties. We will discuss:

Search Trees. The term refers to a family of implementations, that may have different properties. We will discuss: Search Trees CSE 2320 Algorithms and Data Structures Alexandra Stefan Based on slides and notes from: Vassilis Athitsos and Bob Weems University of Texas at Arlington 1 Search Trees Preliminary note: "search

More information

Search Trees. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Binary Search Trees

Search Trees. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Binary Search Trees Unit 9, Part 2 Search Trees Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Binary Search Trees Search-tree property: for each node k: all nodes in k s left subtree are < k all nodes

More information

CSE 373 Autumn 2010: Midterm #1 (closed book, closed notes, NO calculators allowed)

CSE 373 Autumn 2010: Midterm #1 (closed book, closed notes, NO calculators allowed) Name: Email address: CSE 373 Autumn 2010: Midterm #1 (closed book, closed notes, NO calculators allowed) Instructions: Read the directions for each question carefully before answering. We may give partial

More information

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

Operations on Heap Tree The major operations required to be performed on a heap tree are Insertion, Deletion, and Merging. Priority Queue, Heap and Heap Sort In this time, we will study Priority queue, heap and heap sort. Heap is a data structure, which permits one to insert elements into a set and also to find the largest

More information

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

A set of nodes (or vertices) with a single starting point Binary Search Trees Understand tree terminology Understand and implement tree traversals Define the binary search tree property Implement binary search trees Implement the TreeSort algorithm 2 A set of

More information

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

Algorithms in Systems Engineering ISE 172. Lecture 16. Dr. Ted Ralphs Algorithms in Systems Engineering ISE 172 Lecture 16 Dr. Ted Ralphs ISE 172 Lecture 16 1 References for Today s Lecture Required reading Sections 6.5-6.7 References CLRS Chapter 22 R. Sedgewick, Algorithms

More information

Week 2. TA Lab Consulting - See schedule (cs400 home pages) Peer Mentoring available - Friday 8am-12pm, 12:15-1:30pm in 1289CS

Week 2. TA Lab Consulting - See schedule (cs400 home pages) Peer Mentoring available - Friday 8am-12pm, 12:15-1:30pm in 1289CS ASSIGNMENTS h0 available and due before 10pm on Monday 1/28 h1 available and due before 10pm on Monday 2/4 p1 available and due before 10pm on Thursday 2/7 Week 2 TA Lab Consulting - See schedule (cs400

More information

Sorted Arrays. Operation Access Search Selection Predecessor Successor Output (print) Insert Delete Extract-Min

Sorted Arrays. Operation Access Search Selection Predecessor Successor Output (print) Insert Delete Extract-Min Binary Search Trees FRIDAY ALGORITHMS Sorted Arrays Operation Access Search Selection Predecessor Successor Output (print) Insert Delete Extract-Min 6 10 11 17 2 0 6 Running Time O(1) O(lg n) O(1) O(1)

More information

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

COSC 2007 Data Structures II Final Exam. Part 1: multiple choice (1 mark each, total 30 marks, circle the correct answer) COSC 2007 Data Structures II Final Exam Thursday, April 13 th, 2006 This is a closed book and closed notes exam. There are total 3 parts. Please answer the questions in the provided space and use back

More information

! 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 Trees (& Heaps) Week 12 Gaddis: 20 Weiss: 21.1-3 CS 5301 Spring 2015 Jill Seaman 1 Tree: non-recursive definition! Tree: set of nodes and directed edges - root: one node is distinguished as the root -

More information

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

Trees. Q: Why study trees? A: Many advance ADTs are implemented using tree-based data structures. Trees Q: Why study trees? : Many advance DTs are implemented using tree-based data structures. Recursive Definition of (Rooted) Tree: Let T be a set with n 0 elements. (i) If n = 0, T is an empty tree,

More information

Binary Search Trees. Analysis of Algorithms

Binary Search Trees. Analysis of Algorithms Binary Search Trees Analysis of Algorithms Binary Search Trees A BST is a binary tree in symmetric order 31 Each node has a key and every node s key is: 19 23 25 35 38 40 larger than all keys in its left

More information

Course Review for. Cpt S 223 Fall Cpt S 223. School of EECS, WSU

Course Review for. Cpt S 223 Fall Cpt S 223. School of EECS, WSU Course Review for Midterm Exam 1 Cpt S 223 Fall 2011 1 Midterm Exam 1 When: Friday (10/14) 1:10-2pm Where: in class Closed book, closed notes Comprehensive Material for preparation: Lecture slides & in-class

More information

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

CS 234. Module 8. November 15, CS 234 Module 8 ADT Priority Queue 1 / 22 CS 234 Module 8 November 15, 2018 CS 234 Module 8 ADT Priority Queue 1 / 22 ADT Priority Queue Data: (key, element pairs) where keys are orderable but not necessarily distinct, and elements are any data.

More information

Self-Balancing Search Trees. Chapter 11

Self-Balancing Search Trees. Chapter 11 Self-Balancing Search Trees Chapter 11 Chapter Objectives To understand the impact that balance has on the performance of binary search trees To learn about the AVL tree for storing and maintaining a binary

More information

Computer Science 210 Data Structures Siena College Fall Topic Notes: Binary Search Trees

Computer Science 210 Data Structures Siena College Fall Topic Notes: Binary Search Trees Computer Science 10 Data Structures Siena College Fall 018 Topic Notes: Binary Search Trees Possibly the most common usage of a binary tree is to store data for quick retrieval. Definition: A binary tree

More information

! 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 Trees & Heaps Week 12 Gaddis: 20 Weiss: 21.1-3 CS 5301 Fall 2018 Jill Seaman!1 Tree: non-recursive definition! Tree: set of nodes and directed edges - root: one node is distinguished as the root - Every

More information

Midterm solutions. n f 3 (n) = 3

Midterm solutions. n f 3 (n) = 3 Introduction to Computer Science 1, SE361 DGIST April 20, 2016 Professors Min-Soo Kim and Taesup Moon Midterm solutions Midterm solutions The midterm is a 1.5 hour exam (4:30pm 6:00pm). This is a closed

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College November 21, 2018 Outline Outline 1 C++ Supplement 1.3: Balanced Binary Search Trees Balanced Binary Search Trees Outline

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 11: Binary Search Trees MOUNA KACEM mouna@cs.wisc.edu Fall 2018 General Overview of Data Structures 2 Introduction to trees 3 Tree: Important non-linear data structure

More information

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

Trees. Introduction & Terminology. February 05, 2018 Cinda Heeren / Geoffrey Tien 1 Trees Introduction & Terminology Cinda Heeren / Geoffrey Tien 1 Review: linked lists Linked lists are constructed out of nodes, consisting of a data element a pointer to another node Lists are constructed

More information

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

Todays Lecture. Assignment 2 deadline: You have 5 Calendar days to complete. Trees! Todays Lecture Assignment 2 deadline: 11 pm Monday 2/17 President s day. You have 5 Calendar days to complete. Trees What are trees in computer science? Data Structures for Trees Algorithms useful

More information

CS301 - Data Structures Glossary By

CS301 - Data Structures Glossary By CS301 - Data Structures Glossary By Abstract Data Type : A set of data values and associated operations that are precisely specified independent of any particular implementation. Also known as ADT Algorithm

More information

Basic Data Structures (Version 7) Name:

Basic Data Structures (Version 7) Name: Prerequisite Concepts for Analysis of Algorithms Basic Data Structures (Version 7) Name: Email: Concept: mathematics notation 1. log 2 n is: Code: 21481 (A) o(log 10 n) (B) ω(log 10 n) (C) Θ(log 10 n)

More information

Topic 14. The BinaryTree ADT

Topic 14. The BinaryTree ADT Topic 14 The BinaryTree ADT Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary tree implementation Examine a binary tree

More information

CMSC 341. Binary Search Trees CMSC 341 BST

CMSC 341. Binary Search Trees CMSC 341 BST CMSC 341 Binary Search Trees CMSC 341 BST Announcements Homework #3 dues Thursday (10/5/2017) Exam #1 next Thursday (10/12/2017) CMSC 341 BST A Generic Tree CMSC 341 BST Binary Tree CMSC 341 BST The Binary

More information

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

CSE2331/5331. Topic 6: Binary Search Tree. Data structure Operations CSE 2331/5331 CSE2331/5331 Topic 6: Binary Search Tree Data structure Operations Set Operations Maximum Extract-Max Insert Increase-key We can use priority queue (implemented by heap) Search Delete Successor Predecessor

More information

CS 261 Data Structures. AVL Trees

CS 261 Data Structures. AVL Trees CS 261 Data Structures AVL Trees 1 Binary Search Tree Complexity of BST operations: proportional to the length of the path from a node to the root Unbalanced tree: operations may be O(n) E.g.: adding elements

More information

Lecture 6: Analysis of Algorithms (CS )

Lecture 6: Analysis of Algorithms (CS ) Lecture 6: Analysis of Algorithms (CS583-002) Amarda Shehu October 08, 2014 1 Outline of Today s Class 2 Traversals Querying Insertion and Deletion Sorting with BSTs 3 Red-black Trees Height of a Red-black

More information

Copyright 1998 by Addison-Wesley Publishing Company 147. Chapter 15. Stacks and Queues

Copyright 1998 by Addison-Wesley Publishing Company 147. Chapter 15. Stacks and Queues Copyright 1998 by Addison-Wesley Publishing Company 147 Chapter 15 Stacks and Queues Copyright 1998 by Addison-Wesley Publishing Company 148 tos (-1) B tos (1) A tos (0) A A tos (0) How the stack routines

More information

CSC 421: Algorithm Design Analysis. Spring 2013

CSC 421: Algorithm Design Analysis. Spring 2013 CSC 421: Algorithm Design Analysis Spring 2013 Transform & conquer transform-and-conquer approach presorting balanced search trees, heaps Horner's Rule problem reduction 1 Transform & conquer the idea

More information

Binary search trees (chapters )

Binary search trees (chapters ) Binary search trees (chapters 18.1 18.3) Binary search trees In a binary search tree (BST), every node is greater than all its left descendants, and less than all its right descendants (recall that this

More information

Trees. Tree Structure Binary Tree Tree Traversals

Trees. Tree Structure Binary Tree Tree Traversals Trees Tree Structure Binary Tree Tree Traversals The Tree Structure Consists of nodes and edges that organize data in a hierarchical fashion. nodes store the data elements. edges connect the nodes. The

More information

CSE 332: Data Structures & Parallelism Lecture 7: Dictionaries; Binary Search Trees. Ruth Anderson Winter 2019

CSE 332: Data Structures & Parallelism Lecture 7: Dictionaries; Binary Search Trees. Ruth Anderson Winter 2019 CSE 332: Data Structures & Parallelism Lecture 7: Dictionaries; Binary Search Trees Ruth Anderson Winter 2019 Today Dictionaries Trees 1/23/2019 2 Where we are Studying the absolutely essential ADTs of

More information

Binary search trees (chapters )

Binary search trees (chapters ) Binary search trees (chapters 18.1 18.3) Binary search trees In a binary search tree (BST), every node is greater than all its left descendants, and less than all its right descendants (recall that this

More information

Trees. Reading: Weiss, Chapter 4. Cpt S 223, Fall 2007 Copyright: Washington State University

Trees. Reading: Weiss, Chapter 4. Cpt S 223, Fall 2007 Copyright: Washington State University Trees Reading: Weiss, Chapter 4 1 Generic Rooted Trees 2 Terms Node, Edge Internal node Root Leaf Child Sibling Descendant Ancestor 3 Tree Representations n-ary trees Each internal node can have at most

More information

CSE373: Data Structures & Algorithms Lecture 4: Dictionaries; Binary Search Trees. Kevin Quinn Fall 2015

CSE373: Data Structures & Algorithms Lecture 4: Dictionaries; Binary Search Trees. Kevin Quinn Fall 2015 CSE373: Data Structures & Algorithms Lecture 4: Dictionaries; Binary Search Trees Kevin Quinn Fall 2015 Where we are Studying the absolutely essential ADTs of computer science and classic data structures

More information

Chapter 20: Binary Trees

Chapter 20: Binary Trees Chapter 20: Binary Trees 20.1 Definition and Application of Binary Trees Definition and Application of Binary Trees Binary tree: a nonlinear linked list in which each node may point to 0, 1, or two other

More information

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

Binary Tree. Preview. Binary Tree. Binary Tree. Binary Search Tree 10/2/2017. Binary Tree 0/2/ Preview Binary Tree Tree Binary Tree Property functions In-order walk Pre-order walk Post-order walk Search Tree Insert an element to the Tree Delete an element form the Tree A binary tree is a tree

More information

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

Trees (Part 1, Theoretical) CSE 2320 Algorithms and Data Structures University of Texas at Arlington Trees (Part 1, Theoretical) CSE 2320 Algorithms and Data Structures University of Texas at Arlington 1 Trees Trees are a natural data structure for representing specific data. Family trees. Organizational

More information

An AVL tree with N nodes is an excellent data. The Big-Oh analysis shows that most operations finish within O(log N) time

An AVL tree with N nodes is an excellent data. The Big-Oh analysis shows that most operations finish within O(log N) time B + -TREES MOTIVATION An AVL tree with N nodes is an excellent data structure for searching, indexing, etc. The Big-Oh analysis shows that most operations finish within O(log N) time The theoretical conclusion

More information