TREES Lecture 10 CS2110 Spring2014

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

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 2018

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

TREES. Trees - Introduction

Programming II (CS300)

Binary Trees

Data Structure - Binary Tree 1 -

Why Do We Need Trees?

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

Chapter 20: Binary Trees

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

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

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

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

Binary Trees, Binary Search Trees

CSC148 Week 6. Larry Zhang

CMPT 225. Binary Search Trees

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

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

CE 221 Data Structures and Algorithms

Trees. Truong Tuan Anh CSE-HCMUT

Garbage Collection: recycling unused memory

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

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

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

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

CS24 Week 8 Lecture 1

CS 206 Introduction to Computer Science II

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

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

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

MIDTERM EXAMINATION Spring 2010 CS301- Data Structures

CSI33 Data Structures

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

7.1 Introduction. A (free) tree T is A simple graph such that for every pair of vertices v and w there is a unique path from v to w

INF2220: algorithms and data structures Series 1

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

TREES Lecture 12 CS2110 Spring 2019

Trees. CSE 373 Data Structures

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

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

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

Largest Online Community of VU Students

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

CS302 - Data Structures using C++

Chapter 11.!!!!Trees! 2011 Pearson Addison-Wesley. All rights reserved 11 A-1

Chapter 11.!!!!Trees! 2011 Pearson Addison-Wesley. All rights reserved 11 A-1

Trees, Part 1: Unbalanced Trees

Binary Trees Fall 2018 Margaret Reid-Miller

Binary Trees. Examples:

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

Lecture 12 TREES II CS2110 Spring 2018

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

Data Structures and Algorithms

CS61B Lecture #20: Trees. Last modified: Mon Oct 8 21:21: CS61B: Lecture #20 1

Binary Trees. Height 1

CS301 - Data Structures Glossary By

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

Principles of Computer Science

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

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

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

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

Binary Search Trees. See Section 11.1 of the text.

CS350: Data Structures Tree Traversal

Algorithms. Deleting from Red-Black Trees B-Trees

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

1. Stack overflow & underflow 2. Implementation: partially filled array & linked list 3. Applications: reverse string, backtracking

Lecture: Analysis of Algorithms (CS )

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

Algorithms and Data Structures

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

BBM 201 Data structures

Data Structures Brett Bernstein

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

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

Binary Trees. Reading: Lewis & Chase 12.1, 12.3 Eck Programming Course CL I

Trees. Trees. CSE 2011 Winter 2007

Topic 14. The BinaryTree ADT

CmpSci 187: Programming with Data Structures Spring 2015

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

Trees, Binary Trees, and Binary Search Trees

The tree data structure. Trees COL 106. Amit Kumar Shweta Agrawal. Acknowledgement :Many slides are courtesy Douglas Harder, UWaterloo

Recursive Data Structures and Grammars

CSE 214 Computer Science II Introduction to Tree

CMSC 341. Binary Search Trees CMSC 341 BST

Chapter 10: Trees. A tree is a connected simple undirected graph with no simple circuits.

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

BST Implementation. Data Structures. Lecture 4 Binary search trees (BST) Dr. Mahmoud Attia Sakr University of Ain Shams

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

CS61B Lecture #21. A Recursive Structure. Fundamental Operation: Traversal. Preorder Traversal and Prefix Expressions. (- (- (* x (+ y 3))) z)

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

Upcoming ACM Events Linux Crash Course Date: Time: Location: Weekly Crack the Coding Interview Date:

Final Exam Data Structure course. No. of Branches (5)

ITI Introduction to Computing II

COMP Analysis of Algorithms & Data Structures

We have the pointers reference the next node in an inorder traversal; called threads


Transcription:

TREES Lecture 10 CS2110 Spring2014

Readings and Homework 2 Textbook, Chapter 23, 24 Homework: A thought problem (draw pictures!) Suppose you use trees to represent student schedules. For each student there would be a general tree with a root node containing student name and ID. The inner nodes in the tree represent courses, and the leaves represent the times/places where each course meets. Given two such trees, how could you determine whether and where the two students might run into one-another?

Tree Overview 3 Tree: recursive data structure (similar to 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 Binary tree: tree in which each node can have at most two children: a left child and a right child 5 4 2 7 8 9 General tree 5 4 7 8 Not a tree 5 4 2 7 8 Binary tree 5 6 8 List-like tree

Binary Trees were in A1! 4 You have seen a binary tree in A1. A Bee object has a mom and pop. There is an ancestral tree! bee mom pop mom pop mom

Tree Terminology 5 M: root of this tree G: root of the left subtree of M B, H, J, N, S: leaves N: left child of P; S: right child P: parent of N M and G: ancestors of D P, N, S: descendents of W J is at depth 2 (i.e. length of path from root = no. of edges) W is at height 2 (i.e. length of longest path to a leaf) A collection of several trees is called a...? B D G H J M P N W S

Class for Binary Tree Node 6 class TreeNode<T> { private T datum; private TreeNode<T> left, right; } /** Constructor: one node tree with datum x */ public TreeNode (T x) { datum= x; } Points to left subtree Points to right subtree /** Constr: Tree with root value x, left tree lft, right tree rgt */ public TreeNode (T x, TreeNode<T> lft, TreeNode<T> rgt) { datum= x; left= lft; right= rgt; } more methods: getdatum, setdatum, getleft, setleft, etc.

Binary versus general tree 7 In a binary tree each node has exactly two pointers: to the left subtree and to the right subtree Of course one or both could be null In a general tree, a node can have any number of child nodes Very useful in some situations...... one of which will be our assignments!

Class for General Tree nodes 8 5 class GTreeNode { 1. private Object datum; 2. private GTreeCell left; 3. private GTreeCell sibling; 4. appropriate getters/setters } Parent node points directly only to its leftmost child Leftmost child has pointer to next sibling, which points to next sibling, etc. 4 2 7 8 9 7 8 3 1 5 4 2 7 8 9 7 8 3 1 General tree Tree represented using GTreeCell

Applications of Trees 9 Most languages (natural and computer) have a recursive, hierarchical structure This structure is implicit in ordinary textual representation Recursive structure can be made explicit by representing sentences in the language as trees: Abstract Syntax Trees (ASTs) ASTs are easier to optimize, generate code from, etc. than textual representation A parser converts textual representations to AST

Example 10 Expression grammar: E integer E (E + E) In textual representation Parentheses show hierarchical structure Text AST Representation -34-34 (2 + 3) + 2 3 In tree representation Hierarchy is explicit in the structure of the tree ((2+3) + (5+7)) + + + 2 3 5 7

Recursion on Trees 11 Recursive methods can be written to operate on trees in an obvious way Base case empty tree leaf node Recursive case solve problem on left and right subtrees put solutions together to get solution for full tree

Searching in a Binary Tree 12 /** Return true iff x is the datum in a node of tree t*/ public static boolean treesearch(object x, TreeNode t) { if (t == null) return false; if (t.datum.equals(x)) 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 13 /** Return true iff x is the datum in a node of tree t*/ public static boolean treesearch(object x, TreeNode t) { if (t == null) return false; if (t.datum.equals(x)) return true; return treesearch(x, t.left) treesearch(x, t.right); } Important point about t. We can think of it either as (1) One node of the tree OR (2) The subtree that is rooted at t 2 9 0 8 3 5 7

Binary Search Tree (BST) 14 If the tree data are ordered: in every subtree, All left descendents of node come before node All right descendents of node come after node Search is MUCH faster 2 5 8 0 3 7 9 /** Return true iff x if the datum in a node of tree t. Precondition: node is a BST */ public static boolean treesearch (Object x, TreeNode t) { if (t== null) return false; } if (t.datum.equals(x)) return true; if (t.datum.compareto(x) > 0) return treesearch(x, t.left); else return treesearch(x, t.right);

Building a BST 15 To insert a new item Pretend to look for the item jan Put the new node in the place where you fall off the tree This can be done using either recursion or iteration Example apr feb jul jun mar may Tree uses alphabetical order Months appear for insertion in calendar order

What Can Go Wrong? 16 apr A BST makes searches very fast, unless Nodes are inserted in alphabetical order In this case, we re basically building a linked list (with some extra wasted space for the left fields that aren t being used) feb jan jul jun BST works great if data arrives in random order mar may

Printing Contents of BST 17 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 the BST in alpha. order. */ public void show () { show(root); System.out.println(); } /** Print BST t in alpha order */ private static void show(treenode t) { if (t== null) return; show(t.lchild); System.out.print(t.datum); show(t.rchild); }

Tree Traversals 18 Walking over whole tree is a tree traversal Done often enough that there are standard names Previous example: inorder traversal n Process left subtree n Process node n Process right subtree Note: Can do other processing besides printing Other standard kinds of traversals Preorder traversal w Process node w Process left subtree w Process right subtree Postorder traversal w Process left subtree w Process right subtree w Process node Level-order traversal w Not recursive uses a queue

19 Some Useful Methods /** Return true iff node t is a leaf */ public static boolean isleaf(treenode t) { return t!= null && t.left == null && t.right == null; } /** Return height of node t using postorder traversal public static int height(treenode t) { if (t== null) return -1; //empty tree if (isleaf(t)) return 0; return 1 + Math.max(height(t.left), height(t.right)); } /** Return number of nodes in t using postorder traversal */ public static int nnodes(treenode t) { if (t== null) return 0; return 1 + nnodes(t.left) + nnodes(t.right); }

Useful Facts about Binary Trees 20 Max number of nodes at depth d: 2 d depth 0 5 If height of tree is h min number of nodes in tree: h + 1 Max number 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 1 2 4 7 8 5 2 0 4 Height 2, maximum number of nodes 4 Height 2, minimum number of nodes 2

Tree with Parent Pointers 21 In some applications, it is useful to have trees in which nodes can reference their parents 5 Analog of doubly-linked lists 4 7 8 2

Things to Think About 22 What if we want to delete data from a BST? jan A BST works great as long as it s balanced How can we keep it balanced? This turns out to be hard enough to motivate us to create other kinds of trees apr feb jul jun mar may

Suffix Trees 23 Given a string s, a suffix tree for s is a tree such that each edge has a unique label, which is a nonnull substring of s any two edges out of the same node have labels beginning with different characters the labels along any path from the root to a leaf concatenate together to give a suffix of s all suffixes are represented by some path the leaf of the path is labeled with the index of the first character of the suffix in s Suffix trees can be constructed in linear time

Suffix Trees 24 a dabra$ bra $ ra cadabra$ dabra$ $ bra cadabra$ $ cadabra$ $ cadabra$ $ cadabra$ abracadabra$

Suffix Trees 25 Useful in string matching algorithms (e.g., longest common substring of 2 strings) Most algorithms linear time Used in genomics (human genome is ~4GB)

Decision Trees Classification: Attributes (e.g. is CC used more than 200 miles from home?) Values (e.g. yes/no) Follow branch of tree based on value of attribute. Leaves provide decision. Example: Freq Trav? yes Allow yes Allow Should credit card transaction be denied? yes Remote Use? no Hotel? 26 no Deny > $10,000? yes no Deny no Deny

Huffman Trees 27 0 1 0 1 0 e 197 1 0 1 0 e t a s 63 40 26 t 1 0 a 1 s Fixed length encoding 197*2 + 63*2 + 40*2 + 26*2 = 652 Huffman encoding 197*1 + 63*2 + 40*3 + 26*3 = 521

Huffman Compression of Ulysses 28 ' ' 242125 00100000 3 110 'e' 139496 01100101 3 000 't' 95660 01110100 4 1010 'a' 89651 01100001 4 1000 'o' 88884 01101111 4 0111 'n' 78465 01101110 4 0101 'i' 76505 01101001 4 0100 's' 73186 01110011 4 0011 'h' 68625 01101000 5 11111 'r' 68320 01110010 5 11110 'l' 52657 01101100 5 10111 'u' 32942 01110101 6 111011 'g' 26201 01100111 6 101101 'f' 25248 01100110 6 101100 '.' 21361 00101110 6 011010 'p' 20661 01110000 6 011001 28

Huffman Compression of Ulysses 29... '7' 68 00110111 15 111010101001111 '/' 58 00101111 15 111010101001110 'X' 19 01011000 16 0110000000100011 '&' 3 00100110 18 011000000010001010 '%' 3 00100101 19 0110000000100010111 '+' 2 00101011 19 0110000000100010110 original size 11904320 compressed size 6822151 42.7% compression 29

BSP Trees 30 BSP = Binary Space Partition (not related to BST!) Used to render 3D images composed of polygons Each node n has one polygon p as data Left subtree of n contains all polygons on one side of p Right subtree of n contains all polygons on the other side of p Order of traversal determines occlusion (hiding)!

Tree Summary 31 A tree is a recursive data structure Each cell has 0 or more successors (children) Each cell except the root has at exactly one predecessor (parent) All cells are reachable from the root A cell with no children is called a leaf Special case: binary tree Binary tree cells have a left and a right child Either or both children can be null Trees are useful for exposing the recursive structure of natural language and computer programs