Topic 14. The BinaryTree ADT

Similar documents
tree nonlinear Examples

The Binary Search Tree ADT

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

Binary Trees, Binary Search Trees

Principles of Computer Science

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

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

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

TREES. Trees - Introduction

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

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

Introduction to Binary Trees

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. CSE 373 Data Structures

Chapter 20: Binary Trees

Why Do We Need Trees?

CE 221 Data Structures and Algorithms

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

CMPSCI 187: Programming With Data Structures. Lecture #28: Binary Search Trees 21 November 2011

Section 5.5. Left subtree The left subtree of a vertex V on a binary tree is the graph formed by the left child L of V, the descendents

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

CS 206 Introduction to Computer Science II

Binary Trees

Garbage Collection: recycling unused memory

Programming II (CS300)

About This Lecture. Trees. Outline. Recursive List Definition slide 1. Recursive Tree Definition. Recursive List Definition slide 2

Trees. Tree Structure Binary Tree Tree Traversals

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

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

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

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

BBM 201 Data structures

March 20/2003 Jayakanth Srinivasan,

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

CS302 - Data Structures using C++

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

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

CS24 Week 8 Lecture 1

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

Trees, Binary Trees, and Binary Search Trees

Binary Trees Fall 2018 Margaret Reid-Miller

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

Binary Trees. Height 1

Lecture Notes 16 - Trees CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson

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

Trees. Trees. CSE 2011 Winter 2007

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

Trees. Truong Tuan Anh CSE-HCMUT

CSC148 Week 6. Larry Zhang

Data Structures Question Bank Multiple Choice

Topic 18 Binary Trees "A tree may grow a thousand feet tall, but its leaves will return to its roots." -Chinese Proverb

CS 206 Introduction to Computer Science II

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

Stacks, Queues and Hierarchical Collections

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

Binary Trees and Binary Search Trees

Chapter 4 Trees. Theorem A graph G has a spanning tree if and only if G is connected.

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

8. Write an example for expression tree. [A/M 10] (A+B)*((C-D)/(E^F))

Terminology. The ADT Binary Tree. The ADT Binary Search Tree

COSC 2011 Section N. Trees: Terminology and Basic Properties

Lecture 26. Introduction to Trees. Trees

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

Chapter Contents. Trees. Tree Concepts. Hierarchical Organization. Hierarchical Organization. Hierarchical Organization.

Definitions A A tree is an abstract t data type. Topic 17. "A tree may grow a. its leaves will return to its roots." Properties of Trees

Data Structure - Binary Tree 1 -

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

Programming II (CS300)

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

Name CPTR246 Spring '17 (100 total points) Exam 3

Stacks, Queues and Hierarchical Collections. 2501ICT Logan

CSI33 Data Structures

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

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

Tree traversals and binary trees

Successor/Predecessor Rules in Binary Trees

Tree. Virendra Singh Indian Institute of Science Bangalore Lecture 11. Courtesy: Prof. Sartaj Sahni. Sep 3,2010

Definition of a tree. A tree is like a binary tree, except that a node may have any number of children

Algorithms and Data Structures

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

Trees! Ellen Walker! CPSC 201 Data Structures! Hiram College!

12 Abstract Data Types

Tree Data Structures CSC 221

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

Trees. Estruturas de Dados / Programação 2 Árvores. Márcio Ribeiro twitter.com/marciomribeiro. Introduc)on. Hierarchical structure

Introduction to Trees. D. Thiebaut CSC212 Fall 2014

» Access elements of a container sequentially without exposing the underlying representation

Data Structures and Algorithms

Trees Algorhyme by Radia Perlman

Lecture 37 Section 9.4. Wed, Apr 22, 2009

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

CS 127 Fall In our last episode. Yet more fun with binary trees. Tree traversals. Breadth-first traversal

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

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

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

Objectives. In this session, you will learn to:

Lecture Topics. Object Structures. Hierarchical Organization. Tree Concepts. Hierarchical Organization. Hierarchical Organization

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

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

Transcription:

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 example 10-2

Trees A tree is a nonlinear data structure used to represent entities that are in some hierarchical relationship Examples in real life: Family tree Table of contents of a book Class inheritance hierarchy in Java Computer file system (folders and subfolders) Decision trees Top-down design 10-3

Example: Computer File System Root directory of C drive Documents and Settings Program Files My Music Desktop Favorites Start Menu Adobe Microsoft Office 10-4

Tree Definition Tree: a set of elements of the same type such that It is empty Or, it has a distinguished element called the root from which descend zero or more trees (subtrees) What kind of definition is this? What is the base case? What is the recursive part? 10-5

Tree Definition Root Subtrees of the root 10-6

Tree Terminology Interior nodes Root Leaf nodes 10-7

Tree Terminology Nodes: the elements in the tree Edges: connections between nodes Root: the distinguished element that is the origin of the tree There is only one root node in a tree Leaf node: a node without an edge to another node Interior node: a node that is not a leaf node Empty tree has no nodes and no edges 10-8

Tree Terminology Parent or predecessor: the node directly above in the hierarchy A node can have only one parent Child or successor: a node directly below in the hierarchy Siblings: nodes that have the same parent Ancestors of a node: its parent, the parent of its parent, etc. Descendants of a node: its children, the children of its children, etc. 10-9

Discussion Does a leaf node have any children? Does the root node have a parent? How many parents does every node other than the root node have? 10-10

Height of a Tree A path is a sequence of edges leading from one node to another Length of a path: number of edges on the path Height of a (non-empty) tree : length of the longest path from the root to a leaf What is the height of a tree that has only a root node? By convention, the height of an empty tree is -1 10-11

Level of a Node Level of a node : number of edges between root and node It can be defined recursively: Level of root node is 0 Level of a node that is not the root node is level of its parent + 1 Question: What is the level of a node in terms of path length? Question: What is the height of a tree in terms of levels? 10-12

Level of a Node Level 0 Level 1 Level 2 Level 3 10-13

Subtrees Subtree of a node: consists of a child node and all its descendants A subtree is itself a tree A node may have many subtrees 10-14

Subtrees Subtrees of the root node 10-15

Subtrees E Subtrees of the node labeled E 10-16

More Tree Terminology Degree or arity of a node: the number of children it has Degree or arity of a tree: the maximum of the degrees of the tree s nodes 10-17

Binary Trees General tree: a tree each of whose nodes may have any number of children n-ary tree: a tree each of whose nodes may have no more than n children Binary tree: a tree each of whose nodes may have no more than 2 children i.e. a binary tree is a tree with degree (arity) 2 The children (if present) are called the left child and right child 10-18

Recursive definition of a binary tree: it is The empty tree Binary Trees Or, a tree which has a root whose left and right subtrees are binary trees A binary tree is a positional tree, i.e. it matters whether the subtree is left or right 10-19

Binary Tree A B C D E F G H I 10-20

Tree Traversals A traversal of a tree requires that each node of the tree be visited once Example: a typical reason to traverse a tree is to display the data stored at each node of the tree Standard traversal orderings: preorder inorder postorder level-order 10-21

Traversals A B C D E F G H I We ll trace the different traversals using this tree; recursive calls, returns, and visits will be numbered in the order they occur 10-22

Preorder Traversal Start at the root Visit each node, followed by its children; we will choose to visit left child before right Recursive algorithm for preorder traversal: If tree is not empty, Visit root node of tree Perform preorder traversal of its left subtree Perform preorder traversal of its right subtree What is the base case? What is the recursive part? 10-23

Preorder Traversal 6 4 23 3: visit B 16 15 22 5: visit D 17: visit E 8 18 21 28 19 14 20 9: visit H.. 7 10. 1112 2. 30.. 13 1: visit A 24 26 37 44 27: visit F 34 35 36 29: visit I 25: visit C 38... 40 41 31 32 45 33 39: visit G 42 43 Nodes are visited in the order ABDHECFIG 10-24

Start at the root Inorder Traversal Visit the left child of each node, then the node, then any remaining nodes Recursive algorithm for inorder traversal If tree is not empty, Perform inorder traversal of left subtree of root Visit root node of tree Perform inorder traversal of its right subtree 10-25

Inorder Traversal 3 23: visit A 1 24 22 45 14: visit B 37: visit C 2 15 25 38 13 21 5: visit D 18: visit E 6 16 20 26 17 12 19 9: visit H.. 4 7. 8 10. 27.. 11 36 44 33: visit F... 39 40 28 30 32 34 35 29: visit I 31 42 41: visit G 43 Nodes are visited in the order DHBEAIFCG 10-26

Start at the root Postorder Traversal Visit the children of each node, then the node Recursive algorithm for postorder traversal If tree is not empty, Perform postorder traversal of left subtree of root Perform postorder traversal of right subtree of root Visit root node of tree 10-27

Postorder Traversal 3 2 22 21: visit B 14 13 20 12: visit D 19: visit E 5 15 18 25 16 11 17 10: visit H.. 4 6. 7 8 1. 26.. 9 45: visit A 23 24 35 42 34: visit F 31 32 33 30: visit I 43: visit C 36... 37 38 27 28 44 29 39 41: visit G 40 Nodes are visited in the order HDEBIFGCA 10-28

Discussion Note that the relative order of the recursive calls in preorder, inorder and postorder traversals is the same The only differences stem from where the visiting of the root node of a subtree actually takes place 10-29

Level Order Traversal Start at the root Visit the nodes at each level, from left to right Is there a recursive algorithm for a level order traversal? 10-30

Level Order Traversal A B C D E F G H I Nodes will be visited in the order ABCDEFGHI 10-31

Iterative Binary Tree Traversals In recursive tree traversals, the Java call stack keeps track of where we are in the tree (by means of the call frames for each call) In iterative traversals, the programmer needs to keep track! An iterative traversal uses a container to store references to nodes not yet visited Order of visiting will depend on the type of container being used (stack, queue, etc.) 10-32

An Iterative Traversal Algorithm // Assumption: the tree is not empty Create an empty container to hold references to nodes yet to be visited. Put reference to the root node in the container. While the container is not empty { } Remove a reference x from the container. Visit the node x points to. Put references to non-empty children of x in the container. } 10-33

Iterative Binary Tree Traversals Container is a stack: if we push the right successor of a node before the left successor, we get preorder traversal Container is a queue: if we enqueue the left successor before the right, we get a level order traversal Exercise: Trace the iterative tree traversal algorithm using as containers a stack a queue 10-34

Traversal Analysis Consider a binary tree with n nodes How many recursive calls are there at most? For each node, 2 recursive calls at most So, 2*n recursive calls at most So, a traversal is O(n) 10-35

Operations on a Binary Tree What might we want to do with a binary tree? Add an element (but where?) Remove an element (but from where?) Is the tree empty? Get size of the tree (i.e. how many elements) Traverse the tree (in preorder, inorder, postorder, level order) 10-36

Discussion It is difficult to have a general add operation, until we know the purpose of the tree (we will discuss binary search trees later) We could add randomly : go either right or left, and add at the first available spot 10-37

Discussion Similarly, where would a general remove operation remove from? We could arbitrarily choose to remove, say, the leftmost leaf If random choice, what would happen to the children and descendants of the element that was removed? What does the parent of the removed element now point to? What if the removed element is the root? 10-38

Possible Binary Tree Operations Operation removeleftsubtree removerightsubtree removeallelements isempty size contains find tostring iteratorinorder iteratorpreorder iteratorpostorder iteratorlevelorder Description Removes the left subtree of the root Removes the right subtree of the root Removes all elements from the tree Determines whether the tree is empty Determines the number of elements in the tree Determines if a particular element is in the tree Returns a reference to the specified target, if found Returns a string representation of tree s contents Returns an iterator for an inorder traversal Returns an iterator for a preorder traversal Returns an iterator for a postorder traversal Returns an iterator for a levelorder traversal 10-39

Binary Tree Operations Our textbook has a smaller set of operations for the BinaryTreeADT See BinaryTreeADT.java 10-40

UML Description of the BinaryTreeADT interface <<interface>> BinaryTreeADT getroot() isempty( ) size( ) contains( ) find( ) tostring() iteratorinorder( ) iteratorpreorder( ) iteratorpostorder( ) iteratorlevelorder( ) 10-41

Linked Binary Tree Implementation To represent the binary tree, we will use a linked structure of nodes root: reference to the node that is the root of the tree count: keeps track of the number of nodes in the tree First, how will we represent a node of a binary tree? 10-42

Binary Tree Node A binary tree node will contain a reference to a data element references to its left and right children left and right children are binary tree nodes themselves 10-43

BinaryTreeNode class Represents a node in a binary tree Attributes: element: reference to data element left: reference to left child of the node right: reference to right child of the node See BinaryTreeNode.java Note that the attributes here are protected This means that they can be accessed directly from any class that is in the same package as BinaryTreeNode.java 10-44

A BinaryTreeNode Object protected T element; protected BinaryTreeNode<T> left, right; element data object left right Note that either or both of the left and right references could be null 10-45

Attributes: LinkedBinaryTree Class protected BinaryTreeNode<T> root; protected int count; The attributes are protected so that they can be accessed directly in any subclass of the LinkedBinaryTree class We will be looking at a very useful kind of binary tree called a Binary Search Tree later 10-46

LinkedBinaryTree Class Constructors: //Creates empty binary tree public LinkedBinaryTree() { count = 0; root = null; } //Creates binary tree with specified element as its root public LinkedBinaryTree (T element) { count = 1; root = new BinaryTreeNode<T> (element); } 10-47

/* Returns a reference to the specified target element if it is found in this binary tree. Throws an ElementNotFoundException if not found. */ public T find(t targetelement) throws ElementNotFoundException { BinaryTreeNode<T> current = findagain( targetelement, root ); if ( current == null ) throw new ElementNotFoundException("binary tree"); return (current.element); } find method 10-48

Discussion What is element in this statement from the method? return (current.element); If element were private rather than protected in BinaryTreeNode.java, what would be need in order to access it? We will now look at the helper method findagain 10-49

private BinaryTreeNode<T> findagain(t targetelement, BinaryTreeNode<T> next) { if (next == null) return null; if (next.element.equals(targetelement)) return next; BinaryTreeNode<T> temp = findagain(targetelement, next.left); if (temp == null) temp = findagain(targetelement, next.right); return temp; } findagain helper method 10-50

Discussion What kind of method is findagain? What is the base case? There are two! What is the recursive part? 10-51

/* Performs an inorder traversal on this binary tree by calling a recursive inorder method that starts with the root. Returns an inorder iterator over this binary tree */ public Iterator<T> iteratorinorder() { ArrayUnorderedList<T> templist = new ArrayUnorderedList<T>(); } inorder (root, templist); return templist.iterator(); iteratorinorder method 10-52

Discussion iteratorinorder is returning an iterator object It will perform the iteration in inorder But where is that iterator coming from? return templist.iterator(); Let s now look at the helper method inorder 10-53

/* Performs a recursive inorder traversal. Parameters are: the node to be used as the root for this traversal, the temporary list for use in this traversal */ protected void inorder (BinaryTreeNode<T> node, ArrayUnorderedList<T> templist) { if (node!= null) { inorder (node.left, templist); templist.addtorear(node.element); inorder (node.right, templist); } inorder helper method } 10-54

Discussion Recall the recursive algorithm for inorder traversal: If tree is not empty, Perform inorder traversal of left subtree of root Visit root node of tree Perform inorder traversal of its right subtree That s exactly the order that is being implemented here! What is visiting the root node here? 10-55

Discussion The data elements of the tree (i.e. items of type T) are being temporarily added to an unordered list, in inorder order Why use an unordered list?? Why not? We already have this collection, with its iterator operation that we can use! 10-56

Using Binary Trees: Expression Trees Programs that manipulate or evaluate arithmetic expressions can use binary trees to hold the expressions An expression tree represents an arithmetic expression such as (5 3) * 4 + 9 / 2 Root node and interior nodes contain operations Leaf nodes contain operands 10-57

Example: An Expression Tree + * / - 4 9 2 5 3 (5 3) * 4 + 9 / 2 10-58

Evaluating Expression Trees We can use an expression tree to evaluate an expression We start the evaluation at the bottom left What kind of traversal is this? 10-59

Evaluating an Expression Tree * This tree represents the expression + - (9 / 2 + 7) * (8 5) / 7 8 5 9 2 Evaluation is based on postorder traversal: If root node is a leaf, return the associated value. Recursively evaluate expression in left subtree. Recursively evaluate expression in right subtree. Perform operation in root node on these two values, and return result. 10-60

Building an Expression Tree Now we know how to evaluate an expression represented by an expression tree But, how do we build an expression tree? We will build it from the postfix form of the expression Exercise: develop the algorithm by following the diagrams on the next pages 10-61

Building an Expression Tree The algorithm will use a stack of ExpressionTree objects An ExpressionTree is a special case of a binary tree The ExpressionTree constructor has 3 parameters: Reference to data item Reference to left child Reference to right child That's all you need to know to develop the algorithm! 10-62

Build an expression tree from the postfix expression 5 3-4 * 9 + Token 5 Processing Step(s) push(new ExpressionTree(5,null,null)); Expression Tree Stack (top at right) 5 Token 3 Processing Step(s) push(new ExpressionTree(3,null,null)); Expression Tree Stack (top at right) 5 3 10-63

Token - Processing Step(s) op2 = pop op1 = pop push(new ExpressionTree(-,op1,op2)); Expression Tree Stack (top at right) - 5 3 10-64

Token 4 Processing Step(s) push(new ExpressionTree(4,null,null)); Expression Tree Stack (top at right) - 4 5 3 10-65

Token * Processing Step(s) op2 = pop op1 = pop push(new ExpressionTree(*,op1,op2)); Expression Tree Stack (top at right) * - 4 5 3 10-66

Token 9 Processing Step(s) push(new ExpressionTree(9,null,null)); Expression Tree Stack (top at right) * 9-4 5 3 10-67

Token + Processing Step(s) op2 = pop op1 = pop push(new ExpressionTree(+,op1,op2)); Expression Tree Stack (top at right) 5 - + * 9 4 3 End of the expression has been reached, and the full expression tree is the only tree left on the stack 10-68