TREES 11/1/18. Prelim Updates. Data Structures. Example Data Structures. Tree Overview. Tree. Singly linked list: Today: trees!

Similar documents
TREES Lecture 12 CS2110 Spring 2018

TREES Lecture 12 CS2110 Spring 2019

TREES Lecture 12 CS2110 Fall 2016

TREES. Tree Overview 9/28/16. Prelim 1 tonight! Important Announcements. Tree terminology. Binary trees were in A1!

TREES Lecture 10 CS2110 Spring2014

References and Homework ABSTRACT DATA TYPES; LISTS & TREES. Abstract Data Type (ADT) 9/24/14. ADT example: Set (bunch of different values)

Binary Trees

Programming II (CS300)

CS24 Week 8 Lecture 1

If you took your exam home last time, I will still regrade it if you want.

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

Binary Trees, Binary Search Trees

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

Principles of Computer Science

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

TREES. Trees - Introduction

CmpSci 187: Programming with Data Structures Spring 2015

Chapter 20: Binary Trees

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

CSC148 Week 6. Larry Zhang

Lecture 12 TREES II CS2110 Spring 2018

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

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

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

Friday Four Square! 4:15PM, Outside Gates

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

Data Structures in Java

CS 206 Introduction to Computer Science II

Motivation Computer Information Systems Storage Retrieval Updates. Binary Search Trees. OrderedStructures. Binary Search Tree

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

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

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

CS 206 Introduction to Computer Science II

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

Data Structure Lecture#10: Binary Trees (Chapter 5) U Kang Seoul National University

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

CMPSCI 187: Programming With Data Structures. Lecture #26: Binary Search Trees David Mix Barrington 9 November 2012

CS 231 Data Structures and Algorithms Fall Binary Search Trees Lecture 23 October 29, Prof. Zadia Codabux

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

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

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

HEAPS & PRIORITY QUEUES

ITI Introduction to Computing II

Garbage Collection: recycling unused memory

INF2220: algorithms and data structures Series 1

COMP Analysis of Algorithms & Data Structures

Algorithms and Data Structures (INF1) Lecture 8/15 Hua Lu

CS350: Data Structures Tree Traversal

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

ITI Introduction to Computing II

CMSC 341 Lecture 10 Binary Search Trees

Trees Chapter 19, 20. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Lecture 23: Binary Search Trees

Algorithms and Data Structures

CS 206 Introduction to Computer Science II

Tree Structures. Definitions: o A tree is a connected acyclic graph. o A disconnected acyclic graph is called a forest

CMSC 341. Binary Search Trees CMSC 341 BST

Why Do We Need Trees?

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

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

Data Structures and Algorithms

Data Structures and Algorithms for Engineers

COMP Analysis of Algorithms & Data Structures

Trees. CSE 373 Data Structures

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

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

CSE 373 APRIL 17 TH TREE BALANCE AND AVL

Trees. Chapter 6. strings. 3 Both position and Enumerator are similar in concept to C++ iterators, although the details are quite different.

Trees and Tree Traversals. Binary Trees. COMP 210: Object-Oriented Programming Lecture Notes 8. Based on notes by Logan Mayfield

Binary Trees and Huffman Encoding Binary Search Trees

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

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

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

tree nonlinear Examples

Search Structures. Kyungran Kang

Trees. Truong Tuan Anh CSE-HCMUT

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

CS302 - Data Structures using C++

TREES cs2420 Introduction to Algorithms and Data Structures Spring 2015

Trees. Eric McCreath

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

Tree. A path is a connected sequence of edges. A tree topology is acyclic there is no loop.

COMP : Trees. COMP20012 Trees 219

CSI33 Data Structures

Lecture 6: Analysis of Algorithms (CS )

Lecture 32. No computer use today. Reminders: Homework 11 is due today. Project 6 is due next Friday. Questions?

Binary Trees Fall 2018 Margaret Reid-Miller

CE 221 Data Structures and Algorithms

BBM 201 Data structures

Topic 14. The BinaryTree ADT

Binary Search Trees Treesort

Outline. Computer Science 331. Insertion: An Example. A Recursive Insertion Algorithm. Binary Search Trees Insertion and Deletion.

MIDTERM EXAMINATION Spring 2010 CS301- Data Structures

CMSC 341 Lecture 15 Leftist Heaps

CMPT 225. Binary Search Trees

Introduction to Trees. D. Thiebaut CSC212 Fall 2014

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

CS61B Lecture #20. Today: Trees. Readings for Today: Data Structures, Chapter 5. Readings for Next Topic: Data Structures, Chapter 6

Chapter 5. Binary Trees

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

Transcription:

relim Updates Regrades are live until next Thursday @ :9M A few rubric changes are happening Recursion question: -0pts if you continued to print Exception handling write the output of execution of that statement rubrics change in place TREE Lecture C0 Fall 08 3 Data tructures There are different ways of storing data, called data structures Each data structure has operations that it is good at and operations that it is bad at For any application, you want to choose a data structure that is good at the things you do often Example Data tructures 4 Data tructure add(val v) get(int i) contains(val v) Array 3 0!() Linked List 3 0!() add(v): append v to this list get(i): return element at position i in this list contains(v): return true if this list contains v AKA add, lookup, search Tree Tree Overview ingly linked list: ode object Today: trees! 0 int value pointer 4 0 0 6 Tree: data structure with nodes, similar to linked list Each node may have zero or more successors (children) Each node has exactly one predecessor (parent) except the root, which has none All nodes are reachable from root A tree or not a tree? 4 4 8 9 8 9 A tree ot a tree 4 8 6 ot a tree A tree

Tree Terminology () Tree Terminology () 8 the root of the tree (no parents) M M child of M child of M ancestors of B D J D J descendants of B H B H the leaves of the tree (no children) Tree Terminology (3) Tree Terminology (4) 9 0 subtree of M M A node s depth is the length of the path to the root. A tree s (or subtree s) height is the length of the longest path from the root to a leaf. M D J depth B H height D J B H depth 3 height 0 Tree Terminology () Class for general tree nodes Multiple trees: a forest D J B H class Treeode<T> { private T value; private List<Treeode<T>> children; //appropriate constructors, getters, //setters, etc. <T> means user picks a type when they create one (later lecture) arent contains a list of its children 4 8 9 eneral tree 3 8

Class for general tree nodes Binary Trees 3 class Treeode<T> { private T value; private List<Treeode<T>> children; //appropriate constructors, getters, //setters, etc. Java.util.List is an interface! It defines the methods that all implementations must implement. hoever writes this class gets to decide what implementation to use ArrayList? LinkedList? Etc.? 4 3 8 8 9 eneral tree 4 A binary tree is a particularly important kind of tree in which every node as at most two children. In a binary tree, the two children are called the left and right children. 4 8 9 ot a binary tree (a general tree) Binary tree 4 9 Binary trees were in A! Useful facts about binary trees You have seen a binary tree in A. A hd object has one or two advisors. (ote: the advisors are the children.) David ries Friedrich Bauer Fritz Bopp eorg Aumann Fritz auter Erwin Fues Heinrich Tietze Constantin Carathodory 6 Max # of nodes at depth d: d If height of tree is h: min # of nodes: h + max #of nodes: 0 + + h = h+ 0 Height, minimum number of nodes depth 0 9 0 8 3 Height, maximum number of nodes Complete binary tree Every level, except last, is completely filled, nodes on bottom level as far left as possible. o holes. Class for binary tree node Binary versus general tree class Treeode<T> { private T datum; private Treeode<T> left, right; Either might be null if the subtree is empty. /** Constructor: one-node tree with datum d */ public Treeode (T d) {datum= d; left= null; right= null; /** Constr: Tree with root datum d, left tree l, right tree r */ public Treeode (T d, Treeode<T> l, Treeode<T> r) { datum= d; left= l; right= r; // more methods: getvalue, setvalue, getleft, setleft, etc. 8 In a binary tree, each node has up to two pointers: to the left subtree and to the right subtree: One or both could be null, meaning the subtree is empty (remember, a tree is a set of nodes) In a general tree, a node can have any number of child nodes (and they need not be ordered) Very useful in some situations...... one of which may be in an assignment! 3

A Tree is a Recursive Thing Looking at trees recursively 9 A binary tree is either null or an object consisting of a value, a left binary tree, and a right binary tree. Left subtree, which is also a binary tree Binary Tree 9 0 8 3 Right subtree (also a binary tree) Looking at trees recursively Looking at trees recursively value a binary tree left subtree right subtree Looking at trees recursively A Recipe for Recursive Functions 4 value Base case: If the input is easy, just solve the problem directly. Recursive case: et a smaller part of the input (or several parts). Call the function on the smaller value(s). Use the recursive result to build a solution for the full input. 4

A Recipe for Recursive Functions on Binary Trees earching in a Binary Tree 6 an empty tree (null), or possibly a leaf Base case: If the input is easy, just solve the problem directly. /** Return true iff x is the datum in a node of tree t*/ public static boolean treeearch(t x, Treeode<T> t) { if (t == null) return false; if (x.equals(t.datum)) return true; return treeearch(x, t.left) treeearch(x, t.right); Recursive case: et a smaller part of the input (or several parts). Call the function on the smaller value(s). each subtree Use the recursive result to build a solution for the full input. Analog of linear search in lists: given tree and an object, find out if object is stored in tree Easy to write recursively, harder to write iteratively 9 0 e sometimes talk of the root of the tree, t. But we also use t to denote the whole tree. 8 3 Comparing Data tructures Data tructure add(val v) get(int i) Array 3 0 Linked List 3 0 Binary Tree 3!()!() contains(val v)!() Index set by pre-determined traversal order (see slide 36); have to go through the whole tree (no short cut like array indexing) ode you seek could be anywhere in the tree; have to search the whole thing. 8 Binary earch Tree (BT) A binary search tree is a binary tree that is ordered and has no duplicate values. In other words, for every node: All nodes in the left subtree have values that are less than the value in that node, and All values in the right subtree are greater. < A BT is the key to making search way faster. 8 0 3 9 > Building a BT Building a BT 9 To insert a new item: retend to look for the item ut the new node in the place where you fall off the tree 30 insert: January ote: Inserting them chronologically, (January, then February ) but the BT places them alphabetically (Feb comes before Jan, etc.)

Building a BT Building a BT 3 3 insert: February insert: March february Building a BT Building a BT 33 34 insert: April february march february march april june may august july september december november october rinting contents of BT Tree traversals 3 Because of ordering rules for BT, easy to print alphabetically Recursively print left subtree rint the root /** rint BT t in alpha order */ private static void print(treeode<t> t) { if (t == null) return; print(t.left); ystem.out.print(t.value); print(t.right); Recursively print right subtree 36 alking over the whole tree is a tree traversal Done often enough that there are standard names revious example: in-order traversal nrocess left subtree nrocess root nrocess right subtree ote: Can do other processing besides printing Other standard kinds of traversals preorder traversal wrocess root wrocess left subtree wrocess right subtree postorder traversal wrocess left subtree wrocess right subtree wrocess root level-order traversal wot recursive: uses a queue (we ll cover this later) 6

3 Binary earch Tree (BT) Compare binary tree to binary search tree: boolean searchbt(n, v): if n == null, return false if n.v == v, return true return searchbt(n.left, v) searchbt(n.right, v) boolean searchbt(n, v): if n == null, return false if n.v == v, return true if v < n.v return searchbt(n.left, v) else return searchbt(n.right, v) recursive calls recursive call 8 0 3 9 38 Comparing Data tructures Data tructure add(val x) get(int i) Array 3 0 Linked List 3 0 Binary Tree 3 BT 3!()!() contains(val x)!()!(&'()h)!(&'()h)!(&'()h) 39 Inserting in Alphabetical Order 40 Inserting in Alphabetical Order april april august Inserting in Alphabetical Order Insertion Order Matters 4 april august december 4 A balanced binary tree is one where the two subtrees of any node are about the same size. earching a binary search tree takes O(h) time, where h is the height of the tree. In a balanced binary search tree, this is O(log n). But if you insert data in sorted order, the tree becomes imbalanced, so searching is O(n). february

Things to think about 43 hat if we want to delete data from a BT? jan A BT works great as long as it s balanced. There are kinds of trees that can automatically keep themselves balanced as things are inserted! apr feb mar jun jul may 8