The Tree ADT.

Slides:



Advertisements
Similar presentations
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary trees Reading: L&C 9.1 – 9.7.
Advertisements

CS 171: Introduction to Computer Science II
Trees Chapter 8.
1 Chapter 7 Trees. 2 What is a Tree In computer science, a tree is an abstract model of a hierarchical structure A tree consists of nodes with a parent-child.
Chapter 12 Trees. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define trees as data structures Define the terms.
CHAPTER 12 Trees. 2 Tree Definition A tree is a non-linear structure, consisting of nodes and links Links: The links are represented by ordered pairs.
Marc Smith and Jim Ten Eyck
Version TCSS 342, Winter 2006 Lecture Notes Trees Binary Trees Binary Search Trees.
1 Chapter 18 Trees Objective To learn general trees and recursion binary trees and recursion tree traversal.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 9: Trees Java Software Structures: Designing and Using Data.
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.
Chapter 10 Trees – part B.
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
Topic 14 The BinaryTree ADT Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms.
Trees CSCI Objectives Define trees as data structures Define the terms associated with trees Discuss the possible implementations of trees Analyze.
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,
Chapter 10-A Trees Modified
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.
Topic 15 The Binary Search Tree ADT Binary Search Tree A binary search tree (BST) is a binary tree with an ordering property of its elements, such.
1 Trees and Binary Search Trees Using binary trees Definition of a binary search tree Implementing binary search trees –Add Element –Remove Element Using.
Computer Science 112 Fundamentals of Programming II Introduction to Trees.
1 Storing Hierarchical Information Lists, Stacks, and Queues represent linear sequences Data often contain hierarchical relationships that cannot be expressed.
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.
Disusun Oleh : Budi Arifitama Pertemuan ke-8. Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms.
Trees By P.Naga Srinivasu M.tech,(MBA). Basic Tree Concepts A tree consists of finite set of elements, called nodes, and a finite set of directed lines.
M180: Data Structures & Algorithms in Java Trees & Binary Trees Arab Open University 1.
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.
Rooted Tree a b d ef i j g h c k root parent node (self) child descendent leaf (no children) e, i, k, g, h are leaves internal node (not a leaf) sibling.
Trees Ellen Walker CPSC 201 Data Structures Hiram College.
1 Trees General Trees  Nonrecursive definition: a tree consists of a set of nodes and a set of directed edges that connect pairs of nodes.
CMSC 202, Version 5/02 1 Trees. CMSC 202, Version 5/02 2 Tree Basics 1.A tree is a set of nodes. 2.A tree may be empty (i.e., contain no nodes). 3.If.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
TREES General trees Binary trees Binary search trees AVL trees Balanced and Threaded trees.
1 Trees General Trees  Nonrecursive definition: a tree consists of a set of nodes and a set of directed edges that connect pairs of nodes.
18-1 Chapter 18 Binary Trees Data Structures and Design in Java © Rick Mercer.
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.
What is a Tree? Formally, we define a tree T as a set of nodes storing elements such that the nodes have a parent-child relationship, that satisfies the.
Trees Saurav Karmakar
Data Structures and Design in Java © Rick Mercer
Trees Chapter 15.
Lecture 1 (UNIT -4) TREE SUNIL KUMAR CIT-UPES.
CMSC 341 Introduction to Trees 8/3/2007 CMSC 341 Tree Intro.
Fundamentals of Programming II Introduction to Trees
Recursive Objects (Part 4)
Trees Another Abstract Data Type (ADT)
Trees Tree nomenclature Implementation strategies Traversals
Csc 2720 Instructor: Zhuojun Duan
Trees Trees are a very useful data structure. Many different kinds of trees are used in Computer Science. We shall study just a few of these.
CMSC 341 Introduction to Trees.
Data Structures & Algorithm Design
abstract containers sequence/linear (1 to 1) hierarchical (1 to many)
Binary Trees, Binary Search Trees
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
TREES General trees Binary trees Binary search trees AVL trees
Java Software Structures: John Lewis & Joseph Chase
Trees Another Abstract Data Type (ADT)
Trees.
Trees Another Abstract Data Type (ADT)
Trees CMSC 202, Version 5/02.
CMSC 202 Trees.
Binary Trees, Binary Search Trees
CMSC 341 Introduction to Trees CMSC 341 Tree Intro.
Chapter 20: Binary Trees.
Trees.
Binary Trees, Binary Search Trees
Data Structures Using C++ 2E
Cs212: Data Structures Lecture 7: Tree_Part1
Presentation transcript:

The Tree 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

Trees A tree is a nonlinear abstract data type that stores elements in a hierarchy. 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

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

Tree Definition Tree: a set of elements that either it is empty or, it has a distinguished element called the root and zero or more trees (called subtrees of the root) What kind of definition is this? What is the base case? What is the recursive part? Recursive!

Tree Definition Root Subtrees of the root

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 Empty tree has no nodes and no edges

Tree Terminology Root edges nodes

Tree Terminology Parent or predecessor: the node directly above another node in the hierarchy A node can have only one parent Child or successor: a node directly below another node 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.

Tree Terminology Leaf node: a node without children Internal node: a node that is not a leaf node

Tree Terminology Interior or internal nodes Root Leaf nodes

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?

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

Level of a Node Level of a node: number of edges between root and the 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?

Level of a Node Level 0 Level 1 Level 2 Level 3

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

Subtrees E Subtrees of the node labeled E

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

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

Binary Trees Recursive definition of a binary tree: it is The empty tree 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

Binary Tree A B C D E F G H I

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

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

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?

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

Inorder Traversal Start at the root 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

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

Postorder Traversal Start at the root 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

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

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

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?

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

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.)

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. }

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

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)

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) traversals

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

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?

Possible Binary Tree Operations Description removeLeftSubtree Removes the left subtree of the root removeRightSubtree Removes the right subtree of the root removeAllElements Removes all elements from the tree isEmpty Determines whether the tree is empty size Determines the number of elements in the tree contains Determines if a particular element is in the tree find Returns a reference to the specified target, if found toString Returns a string representation of tree’s contents iteratorInOrder Returns an iterator for an inorder traversal iteratorPreOrder Returns an iterator for a preorder traversal iteratorPostOrder Returns an iterator for a postorder traversal iteratorLevelOrder Returns an iterator for a levelorder traversal

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

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?

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

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

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

LinkedBinaryTree Class Attributes: 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

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);

/* 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

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 …

findAgain helper method 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

Discussion What kind of method is findAgain? What is the base case? There are two! What is the recursive part?

iteratorInOrder method /* 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

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 …

/. Performs a recursive inorder traversal /* 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

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?

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!

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

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

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? Postorder

Evaluating an Expression Tree * This tree represents the expression (9 / 2 + 7) * (8 – 5) + - / 7 8 5 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. 9 2

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

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!

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

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

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

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

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

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