TREES Lecture 12 CS2110 Spring 2018

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

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 12 CS2110 Spring 2019

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)

Lecture 12 TREES II CS2110 Spring 2018

Binary Trees

Programming II (CS300)

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

CS24 Week 8 Lecture 1

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

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

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

Binary Trees, Binary Search Trees

TREES. Trees - Introduction

Chapter 20: Binary Trees

CmpSci 187: Programming with Data Structures Spring 2015

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

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

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

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

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

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

Friday Four Square! 4:15PM, Outside Gates

Garbage Collection: recycling unused memory

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

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

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

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

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

Principles of Computer Science

Data Structures in Java

Lecture 23: Binary Search Trees

Lecture 34. Wednesday, April 6 CS 215 Fundamentals of Programming II - Lecture 34 1

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

COMP Analysis of Algorithms & Data Structures

INF2220: algorithms and data structures Series 1

CMPT 225. Binary Search Trees

CSC148 Week 6. Larry Zhang

Lecture 6: Analysis of Algorithms (CS )

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

COMP Analysis of Algorithms & Data Structures

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

Data Structures Brett Bernstein

Data Structures and Algorithms for Engineers

Search Structures. Kyungran Kang

Why Do We Need Trees?

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

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

Data Structures and Algorithms

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

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

Trees. Truong Tuan Anh CSE-HCMUT

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

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

CSI33 Data Structures

CS302 - Data Structures using C++

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

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

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

Trees, Part 1: Unbalanced Trees

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

Algorithms and Data Structures

CMSC 341. Binary Search Trees CMSC 341 BST

CS350: Data Structures Tree Traversal

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

MIDTERM EXAMINATION Spring 2010 CS301- Data Structures

ITI Introduction to Computing II

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

CS211, LECTURE 20 SEARCH TREES ANNOUNCEMENTS:

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

ITI Introduction to Computing II

Binary Search Trees Treesort

Binary Search Trees 1

CMSC 341 Lecture 10 Binary Search Trees

Search Trees: BSTs and B-Trees

CS 206 Introduction to Computer Science II

Some Search Structures. Balanced Search Trees. Binary Search Trees. A Binary Search Tree. Review Binary Search Trees

Binary Search Trees. See Section 11.1 of the text.

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

Programming Languages and Techniques (CIS120)

CS2110 Assignment 3 Inheritance and Trees, Summer 2008

CS 206 Introduction to Computer Science II

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

SFU CMPT Lecture: Week 9

CSE 373 APRIL 17 TH TREE BALANCE AND AVL

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

Chapter 5. Binary Trees

Largest Online Community of VU Students

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

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

Data Structure - Binary Tree 1 -

COMP : Trees. COMP20012 Trees 219

Binary Trees and Huffman Encoding Binary Search Trees

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

CS 206 Introduction to Computer Science II

Recursion, Binary Trees, and Heaps February 18

CSCI-1200 Data Structures Spring 2015 Lecture 20 Trees, Part III

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

Transcription:

TREES Lecture 12 CS2110 Spring 2018

Important Announcements 2 A4 is out now and due two weeks from today. Have fun, and start early!

Data Structures 3 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 Structures 4 Data Structure add(val x) lookup(int i) Array 2 1 3 0 Linked List 2 1 3 0 O(n) O(1) O(1) O(n)

5 The Problem of Search

Example Data Structures 6 Data Structure add(val x) lookup(int i) Array 2 1 3 0 Linked List 2 1 3 0 O(n) O(1) O(1) O(n) search(val x) O(n) O(n)

Tree 7 Singly linked list: 2 1 1 0 Node object int value pointer 0 Today: trees! 2 1 4 1 1 0 1

Tree Overview 8 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 5 4 2 7 8 9 A tree 5 4 5 4 2 7 8 9 Not a tree 5 6 7 8 Not a tree 8 A tree

Tree Terminology 9 the root of the tree (no parents) M child of M G W child of M D J P B H N S the leaves of the tree (no children)

Tree Terminology 10 M ancestors of B G W D J P descendants of W B H N S

Tree Terminology 11 M subtree of M G W D J P B H N S

Tree Terminology 12 A node s depth is the length of the path to the root. A tree s (or subtree s) height is he length of the longest path from the root to a leaf. M G W Depth 1, height 2. D J P Depth 3, height 0. B H N S

Tree Terminology 13 Multiple trees: a forest. G W D J P B H N S

Class for general tree nodes 14 class GTreeNode<T> { private T value; private List<GTreeNode<T>> children; //appropriate constructors, getters, //setters, etc. } Parent contains a list of its children 5 4 2 7 8 9 General tree 7 8 3 1

Class for general tree nodes 15 class GTreeNode<T> { private T value; private List<GTreeNode<T>> children; //appropriate constructors, getters, //setters, etc. } Java.util.List is an interface! It defines the methods that all implementation must implement. Whoever writes this class gets to decide what implementation to use ArrayList? LinkedList? Etc.? 4 5 7 8 9 2 7 8 3 1 General tree

Binary Trees 16 A binary tree is a particularly important kind of tree where every node as at most two children. In a binary tree, the two children are called the left and right children. 4 5 7 8 9 2 Not a binary tree (a general tree) 5 4 2 7 8 Binary tree

Binary trees were in A1! 17 You have seen a binary tree in A1. A PhD object has one or two advisors. (Confusingly, the advisors are the children. ) David Gries Friedrich Bauer Fritz Bopp Georg Aumann Fritz Sauter Erwin Fues Heinrich Tietze Constantin Carathodory

Class for binary tree node 18 class TreeNode<T> { private T value; private TreeNode<T> left, right; } Either might be null if the subtree is empty. /** Constructor: one-node tree with datum x */ public TreeNode (T d) { datum= d; left= null; right= null;} /** Constr: Tree with root value x, left tree l, right tree r */ public TreeNode (T d, TreeNode<T> l, TreeNode<T> r) { datum= d; left= l; right= r; } more methods: getvalue, setvalue, getleft, setleft, etc.

Binary versus general tree 19 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!

A Tree is a Recursive Thing 20 A binary tree is either null or an object consisting of a value, a left binary tree, and a right binary tree.

Looking at trees recursively 21 Binary tree 9 2 0 Right subtree (also a binary tree) 8 3 5 7 Left subtree, which is a binary tree too

Looking at trees recursively a binary tree

Looking at trees recursively value left subtree right subtree

Looking at trees recursively value

A Recipe for Recursive Functions 25 Base case: If the input is easy, just solve the problem directly. Recursive case: Get 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.

Recursive Functions on Binary Trees 26 Base case: empty tree (null) or, possibly, a leaf Recursive case: Call the function on each subtree. Use the recursive result to build a solution for the full input.

Searching in a Binary Tree 27 /** Return true iff x is the datum in a node of tree t*/ public static boolean treesearch(t x, TreeNode<T> t) { if (t == null) return false; if (x.equals(t.datum)) return true; return treesearch(x, t.left) treesearch(x, t.right); } 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 2 9 0 8 3 5 7

Searching in a Binary Tree 28 /** Return true iff x is the datum in a node of tree t*/ public static boolean treesearch(t x, TreeNode<T> t) { if (t == null) return false; if (x.equals(t.datum)) return true; return treesearch(x, t.left) treesearch(x, t.right); } VERY IMPORTANT! We sometimes talk of t as the root of the tree. But we also use t to denote the whole tree. 2 9 0 8 3 5 7

Comparing Data Structures 29 Data Structure add(val x) lookup(int i) search(val x) Array 2 1 3 0 Linked List 2 1 3 0 Binary Tree 2 O(n) O(1) O(n) O(1) O(n) O(n) 1 3 O(1) O(n) O(n)

Binary Search Tree (BST) 30 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. 5 < 5 2 8 > 5 0 3 7 9 A BST is the key to making search way faster.

Building a BST 31 To insert a new item: Pretend to look for the item Put the new node in the place where you fall off the tree

Building a BST 32 january

Building a BST 33 january

Building a BST 34 january february

Building a BST 35 january february

Building a BST 36 january february

Building a BST 37 january march february

Building a BST 38 january february march

Building a BST 39 january april february march

Building a BST 40 january april february march

Building a BST 41 january february march april

Building a BST 42 january february march april

Building a BST 43 january february march april june may august july september december november october

Printing contents of BST 44 Because of ordering rules for a BST, it s easy to print the items in alphabetical order Recursively print left subtree Print the node Recursively print right subtree /** Print BST t in alpha order */ private static void print(treenode<t> t) { if (t== null) return; print(t.left); System.out.print(t.value); print(t.right); }

Tree traversals 45 Walking over the whole tree is a tree traversal Done often enough that there are standard names Previous example: in-order traversal nprocess left subtree nprocess root nprocess right subtree Note: Can do other processing besides printing Other standard kinds of traversals preorder traversal wprocess root wprocess left subtree wprocess right subtree postorder traversal wprocess left subtree wprocess right subtree wprocess root level-order traversal wnot recursive: uses a queue (we ll cover this later)

Binary Search Tree (BST) 46 5 2 8 0 3 7 9 Compare binary tree to binary search tree: boolean searchbt(n, v): if n==null, return false if n.v == v, return true return searchbst(n.left, v) searchbst(n.right, v) boolean searchbst(n, v): if n==null, return false if n.v == v, return true if v < n.v return searchbst(n.left, v) else return searchbst(n.right, v) 2 recursive calls 1 recursive call

Comparing Data Structures 47 Data Structure add(val x) lookup(int i) Array 2 1 3 0 Linked List 2 1 3 0 Binary Tree BST 1 O(n) O(1) O(1) O(n) search(val x) O(n) O(n) 2 3 O(1) O(n) O(n) 2 1 3 O(depth) O(depth) O(depth)

Inserting in Alphabetical Order 48 april

Inserting in Alphabetical Order 49 april

Inserting in Alphabetical Order 50 april august

Inserting in Alphabetical Order 51 april august

Inserting in Alphabetical Order 52 april august december

Inserting in Alphabetical Order 53 april august december february january

Insertion Order Matters 54 A balanced binary tree is one where the two subtrees of any node are about the same size. Searching 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).

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

Useful facts about binary trees 56 Max # of nodes at depth d: 2 d If height of tree is h min # of nodes: h + 1 max #of nodes in tree: 2 0 + + 2 h = 2 h+1 1 Complete binary tree All levels of tree down to a certain depth are completely filled depth 0 1 2 4 7 8 5 5 2 0 4 Height 2, maximum number of nodes 2 4 Height 2, minimum number of nodes