TREES Lecture 12 CS2110 – Fall 2015. Announcements  Prelim #1 is tonight!  Olin 155  A-L  5:30  M-Z  5:30  A4 will be posted today  Mid-semester.

Slides:



Advertisements
Similar presentations
Comp 122, Spring 2004 Binary Search Trees. btrees - 2 Comp 122, Spring 2004 Binary Trees  Recursive definition 1.An empty tree is a binary tree 2.A node.
Advertisements

1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
TREES Chapter 6. Trees - Introduction  All previous data organizations we've studied are linear—each element can have only one predecessor and successor.
Binary Trees Chapter 6. Linked Lists Suck By now you realize that the title to this slide is true… By now you realize that the title to this slide is.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
CS 171: Introduction to Computer Science II
Data Structures Data Structures Topic #8. Today’s Agenda Continue Discussing Table Abstractions But, this time, let’s talk about them in terms of new.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Trees Weiss sec (preview) ch. 18 (sort of).
1 General Trees & Binary Trees CSC Trees Previous data structures (e.g. lists, stacks, queues) have a linear structure. Linear structures represent.
Week 7 - Wednesday.  What did we talk about last time?  Recursive running time  Master Theorem  Introduction to trees.
ABSTRACT DATA TYPES; LISTS & TREES Lecture 10 CS2110 – Fall 2014.
Binary Trees Chapter 6.
CS 146: Data Structures and Algorithms June 18 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Trees Chapter 8. 2 Tree Terminology A tree consists of a collection of elements or nodes, organized hierarchically. The node at the top of a tree is called.
Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary search trees.
Tree. Basic characteristic Top node = root Left and right subtree Node 1 is a parent of node 2,5,6. –Node 2 is a parent of node.
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
S EARCHING AND T REES COMP1927 Computing 15s1 Sedgewick Chapters 5, 12.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
CMSC 341 Introduction to Trees. 8/3/2007 UMBC CMSC 341 TreeIntro 2 Tree ADT Tree definition  A tree is a set of nodes which may be empty  If not empty,
Tree (new ADT) Terminology:  A tree is a collection of elements (nodes)  Each node may have 0 or more successors (called children)  How many does a.
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
TREES. What is a tree ? An Abstract Data Type which emulates a tree structure with a set of linked nodes The nodes within a tree are organized in a hierarchical.
CS 206 Introduction to Computer Science II 02 / 13 / 2009 Instructor: Michael Eckmann.
Data Structures TREES.
CSC 143 Trees [Chapter 10].
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
CMSC 341 Introduction to Trees. 2/21/20062 Tree ADT Tree definition –A tree is a set of nodes which may be empty –If not empty, then there is a distinguished.
Binary Tree. Some Terminologies Short review on binary tree Tree traversals Binary Search Tree (BST)‏ Questions.
1/14/20161 BST Operations Data Structures Ananda Gunawardena.
TREES K. Birman’s and G. Bebis’s Slides. Tree Overview 2  Tree: recursive data structure (similar to list)  Each cell may have zero or more successors.
Week 7 - Wednesday.  What did we talk about last time?  Recursive running time  Master Theorem  Symbol tables.
1 Trees. Objectives To understand the concept of trees and the standard terminology used to describe them. To appreciate the recursive nature of a tree.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
CS Prelim Review – 10/15/09  First prelim is TOMORROW at 7:30 PM  Review session – Tonight 7:30 PM, Phillips 101  Things you should do:  Review every.
TREES Lecture 11 CS2110 – Spring Readings and Homework  Textbook, Chapter 23, 24  Homework: A thought problem (draw pictures!)  Suppose you use.
1 CSE 326: Data Structures Trees Lecture 6: Friday, Jan 17, 2003.
353 3/30/98 CSE 143 Trees [Sections , 13.6,13.8]
18-1 Chapter 18 Binary Trees Data Structures and Design in Java © Rick Mercer.
Fundamentals of Algorithms MCS - 2 Lecture # 17. Binary Search Trees.
1 CMSC 341 Introduction to Trees Textbook sections:
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture13.
(c) University of Washington20-1 CSC 143 Java Trees.
CSE 373 Data Structures Lecture 7
Trees Chapter 15.
CC 215 Data Structures Trees
Recursive Objects (Part 4)
Trees Lecture 12 CS2110 – Spring 2017.
Week 6 - Wednesday CS221.
Trees Lecture 12 CS2110 – Fall 2017.
Trees Lecture 12 CS2110 – Fall 2016.
CSE 373 Data Structures Lecture 7
abstract containers sequence/linear (1 to 1) hierarchical (1 to many)
Binary Trees, Binary Search Trees
Trees Lecture 12 CS2110 – Spring 2018.
Find in a linked list? first last 7  4  3  8 NULL
Trees CSE 373 Data Structures.
Trees.
Trees Lecture 9 CS2110 – Fall 2009.
Trees Lecture 12 CS2110 – Fall 2018.
Announcements Prelim 1 on Tuesday! A4 will be posted today
CSC 143 Java Trees.
Tree.
Trees.
Trees CSE 373 Data Structures.
Trees Lecture 10 CS2110 – Spring 2013.
Presentation transcript:

TREES Lecture 12 CS2110 – Fall 2015

Announcements  Prelim #1 is tonight!  Olin 155  A-L  5:30  M-Z  5:30  A4 will be posted today  Mid-semester TA evaluations are coming up; please participate! Your feedback will help our staff improve their teaching. 2

Outline  A4 Preview  Introduction to Trees 3

Readings and Homework  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? 4

Tree Overview 5 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 General tree Binary tree Not a tree List-like tree

Binary trees were in A1! You have seen a binary tree in A1. A PhD object phd has one or two advisors. Here is an intellectual ancestral tree! phd ad1 ad2 ad1 ad2 ad1 6

Tree terminology 7 M: root of this tree G: root of the left subtree of M B, H, J, N, S: leaves (their set of children is empty) N: left child of P; S: right child of P 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...? MGWPJDNHBS

Class for binary tree node 8 class TreeNode { private T datum; private TreeNode left, right; /** Constructor: one node tree with datum x */ public TreeNode (T d) { datum= d; } /** Constr: Tree with root value x, left tree l, right tree r */ public TreeNode (T d, TreeNode l, TreeNode r) { datum= d; left= l; right= r; } Points to left subtree (null if empty) Points to right subtree (null if empty) more methods: getDatum, setDatum, getLeft, setLeft, etc.

Binary versus general tree In a binary tree, each node has exactly 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! 9

Class for general tree nodes 10 class GTreeNode { 1. Private T datum; 2. private GTreeNode [] children; 3. //appropriate constructors, getters, 4. //setters, etc. } General tree Parent contains an array of its children

Applications of Trees 11  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

Use of trees: Represent expressions 12 In textual representation: Parentheses show hierarchical structure In tree representation: Hierarchy is explicit in the structure of the tree We’ll talk more about expression and trees on Thursday (2 + 3) ((2+3) + (5+7)) TextTree Representation -

Recursion on trees 13 Trees are defined recursively. So recursive methods can be written to process trees in an obvious way Base case  empty tree (null)  leaf Recursive case  solve problem on left / right subtrees  put solutions together to get solution for full tree

Searching in a Binary Tree 14 /** Return true iff x is the datum in a node of tree t*/ public static boolean treeSearch(Tx, 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

Binary Search Tree (BST) 15 If the tree data are ordered and no duplicate values: in every subtree, All left descendents of node come before node All right descendents o f node come after node Search is MUCH faster /** Return true iff x if the datum in a node of tree t. Precondition: node is a BST */ public static boolean treeSearch (T 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 16  To insert a new item  Pretend to look for the item  Put the new node in the place where you fall off the tree  This can be done using either recursion or iteration  Example  Tree uses alphabetical order  Months appear for insertion in calendar order janfebmaraprmayjunjul

What can go wrong? 17 A BST makes searches very fast, unless…  Nodes are inserted in increasing order  In this case, we’re basically building a linked list (with some extra wasted space for the left fields, which aren’t being used) BST works great if data arrives in random order jan feb mar apr may jun jul

Printing contents of BST 18 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) { if (t== null) return; print(t.left); System.out.print(t.datum); print(t.right); }

Tree traversals “Walking” over whole tree is a tree traversal  Done often enough that there are standard names Previous example: inorder traversal Process left subtree Process root Process right subtree Note: Can do other processing besides printing Other standard kinds of traversals  preorder traversal  Process root  Process left subtree  Process right subtree  postorder traversal  Process left subtree  Process right subtree  Process root  level-order traversal  Not recursive uses a queue. We discuss later 19

Some useful methods 20 /** 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 (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 (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 21 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 h = 2 h+1 – 1 Complete binary tree  All levels of tree down to a certain depth are completely filled depth Height 2, minimum number of nodes Height 2, maximum number of nodes

Things to think about 22 What if we want to delete data from a BST? 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 janfebmaraprmayjunjul

Tree Summary 23  A tree is a recursive data structure  Each node has 0 or more successors (children)  Each node except the root has at exactly one predecessor (parent)  All node are reachable from the root  A node with no children (or empty children) is called a leaf  Special case: binary tree  Binary tree nodes have a left and a right child  Either or both children can be empty (null)  Trees are useful in many situations, including exposing the recursive structure of natural language and computer programs