Binary Tree Applications Chapter 6.6 1. 107 - Trees Parse Trees What is parsing? Originally from language study The breaking up of sentences into component.

Slides:



Advertisements
Similar presentations
Expression Trees What is an Expression tree? Expression tree implementation Why expression trees? Evaluating an expression tree (pseudo code) Prefix, Infix,
Advertisements

Trees Chapter 8.
Trees Chapter Chapter Contents Tree Concepts Hierarchical Organizations Tree Terminology Traversals of a Tree Traversals of a Binary Tree Traversals.
Fall 2007CS 2251 Trees Chapter 8. Fall 2007CS 2252 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information.
9/27/2006Prof. Hilfinger, Lecture 141 Syntax-Directed Translation Lecture 14 (adapted from slides by R. Bodik)
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
1 Introduction to Binary Trees. 2 Background All data structures examined so far are linear data structures. Each element in a linear data structure has.
Lec 15 April 9 Topics: l binary Trees l expression trees Binary Search Trees (Chapter 5 of text)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L12 (Chapter 20) Lists, Stacks,
Transforming Infix to Postfix
Binary Search Trees Section Trees Trees are efficient Many algorithms can be performed on trees in O(log n) time. Searching for elements.
Chapter 18 - basic definitions - binary trees - tree traversals Intro. to Trees 1CSCI 3333 Data Structures.
1 Chapter 18 Trees Objective To learn general trees and recursion binary trees and recursion tree traversal.
Computer Science 112 Fundamentals of Programming II Expression Trees.
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.
Trees. Tree Terminology Chapter 8: Trees 2 A tree consists of a collection of elements or nodes, with each node linked to its successors The node at the.
(c) University of Washington20d-1 CSC 143 Java Applications of Trees.
Chapter 19: Binary Trees. Objectives In this chapter, you will: – Learn about binary trees – Explore various binary tree traversal algorithms – Organize.
Trees.ppt1 Introduction Many data structures are linear –unique first component –unique last component –other components have unique predecessor and successor.
1 EXPRESSION TREES In this lecture we will discuss Expression trees as a method for storing & evaluating mathematical expressions.
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
Data Structures : Project 5 Data Structures Project 5 – Expression Trees and Code Generation.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Chapter 19 Implementing Trees and Priority Queues Fundamentals of Java.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
Chapter 19 Implementing Trees and Priority Queues Fundamentals of Java.
Binary Trees 2 Overview Trees. Terminology. Traversal of Binary Trees. Expression Trees. Binary Search Trees.
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.
Interpretation Environments and Evaluation. CS 354 Spring Translation Stages Lexical analysis (scanning) Parsing –Recognizing –Building parse tree.
Compiled by: Dr. Mohammad Omar Alhawarat
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.
Starting at Binary Trees
Computer Science 112 Fundamentals of Programming II Introduction to Trees.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 19 Binary Search Trees.
Binary Search Trees (BST)
Traversing a tree means visiting each node in a specified order. There are different ways to traverse a tree. Tree Traversing Depth first search Pre-orderIn-orderPost-order.
Chapter 10: Trees A tree is a connected simple undirected graph with no simple circuits. Properties: There is a unique simple path between any 2 of its.
1 Trees 2 Binary trees Section Binary Trees Definition: A binary tree is a rooted tree in which no vertex has more than two children –Left and.
Copyright © 2012 Pearson Education, Inc. Chapter 20: Binary Trees.
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.
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.
DS.T.1 Trees Chapter 4 Overview Tree Concepts Traversals Binary Trees Binary Search Trees AVL Trees Splay Trees B-Trees.
SUYASH BHARDWAJ FACULTY OF ENGINEERING AND TECHNOLOGY GURUKUL KANGRI VISHWAVIDYALAYA, HARIDWAR.
Trees Saurav Karmakar
Chapter 12 – Data Structures
Chapter 10 Trees © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Fundamentals of Programming II Introduction to Trees
Recursive Objects (Part 4)
Tree.
Section 8.1 Trees.
Podcast Ch17a Title: Expression Trees
Tonga Institute of Higher Education
Binary Tree Application Expression Tree
i206: Lecture 13: Recursion, continued Trees
Binary Tree and General Tree
Chapter 20: Binary Trees.
Chapter 21: Binary Trees.
CS212: Data Structures and Algorithms
Trees.
CSC 143 Java Applications of Trees.
CSC 143 Java Trees.
Trees.
Chapter 20: Binary Trees.
Binary Tree Application Build Expression Tree Heaps
Introduction to Trees Chapter 6 Objectives
Binary Tree Iterators Tree Traversals: preorder, inorder, postorder
Presentation transcript:

Binary Tree Applications Chapter 6.6 1

107 - Trees Parse Trees What is parsing? Originally from language study The breaking up of sentences into component parts e.g. noun phrase In computing compilers and interpreters parse programming languages. One aspect is parsing expressions. 2

107 - Trees Expression Trees The leaves are values and the other nodes are operators. We can use them to represent and evaluate the expression. We work up from the bottom evaluating subtrees. Compilers can use this to generate efficient code - e.g. how many registers are needed to calculate this expression. 3

107 - Trees Tokens Parsing starts with recognising tokens. A token is a symbol made up of one or more characters (commonly separated by white space). e.g. a variable name or a number or an operator “+”. For an expression tree the tokens are numbers, operators and parentheses. 4

107 - Trees Parsing Rules As we identify tokens we can apply rules to what we should do. If the expression is fully parenthesised a left parenthesis “(“ starts a subtree a right parenthesis “)” finishes a subtree 5

107 - Trees 4 Rules 1.If the current token is a ‘(’, add a new node as the left child of the current node, and descend to the left child. 2.If the current token is in the list [‘+’,’−’,’*’,‘/’], set the root value of the current node to the operator represented by the current token. Add a new node as the right child of the current node and descend to the right child. 3.If the current token is a number, set the root value of the current node to the number and return to the parent. 4.If the current token is a ‘)’, go to the parent of the current node. 6

107 - Trees (3 + (4 * 5)) 7 Current node

107 - Trees (3 + (4 * 5)) 8 Current node

107 - Trees (3 + (4 * 5)) 9 3 Current node

107 - Trees (3 + (4 * 5)) Current node

107 - Trees (3 + (4 * 5)) Current node

107 - Trees (3 + (4 * 5)) Current node

107 - Trees (3 + (4 * 5)) * 4

107 - Trees (3 + (4 * 5)) * 45 Current node

107 - Trees (3 + (4 * 5)) * 45 Current node

107 - Trees (3 + (4 * 5)) * 45

107 - Trees Your turn 17 Generate the expression tree for ((2 * ((3 - 4) + 6)) + 2)

107 - Trees Keeping Track of the Parent We need to be able to move back up the tree. So we need to keep track of the parent of the current working node. We could do this with links from each child node back to its parent. Or we could store the tree in a list and use the 2 x n trick (if the tree is not complete - most won’t be) then there will be lots of empty space in this list. Or we could push the parent node onto a stack as we move down the tree and pop parent nodes off the stack when we move back up. 18

107 - Trees Build the tree code set up def build_expression_tree(parenthesized_expression): """Builds an expression parse tree. parenthesized_expression -- a fully parenthesized expression with spaces between tokens """ token_list = parenthesized_expression.split() parent_stack = Stack() expression_tree = BinaryTree('') parent_stack.push(expression_tree) current_tree = expression_tree 19

107 - Trees Implementing the rules for token in token_list: if token == '(': current_tree.insert_left('') parent_stack.push(current_tree) current_tree = current_tree.get_left_child() 20 1.If the current token is a ‘(’, add a new node as the left child of the current node, and descend to the left child.

107 - Trees Implementing the rules elif token in ['+', '-', '*', '/']: current_tree.set_value(token) current_tree.insert_right('') parent_stack.push(current_tree) current_tree = current_tree.get_right_child() 21 2.If the current token is in the list [‘+’,‘−’,‘*’,‘/’], set the root value of the current node to the operator represented by the current token. Add a new node as the right child of the current node and descend to the right child.

107 - Trees Implementing the rules elif is_number(token): current_tree.set_value(float(token)) current_tree = parent_stack.pop() 22 3.If the current token is a number, set the root value of the current node to the number and return to the parent. def is_number(token): """Check if the token is a number.""" try: float(token) except: return False else: return True

107 - Trees Implementing the rules elif token == ')': current_tree = parent_stack.pop() else: raise ValueError 23 4.If the current token is a ‘)’, go to the parent of the current node.

107 - Trees Evaluating the expression Once we have generated the expression tree we can easily evaluate the expression. In a compiler the expression would contain variables which we wouldn’t know the value of until the program ran, so the evaluation would be done at run time. 24

107 - Trees How would you evaluate? * 45 evaluate this subtree

107 - Trees Algorithm To evaluate the subtree under a node if the node has children the node holds an operator return the result of applying the operator on the left and right subtrees else the node held a number return the number 26

107 - Trees Evaluation Code import operator def evaluate(expression_tree): """Return the result of evaluating the expression.""" token = expression_tree.get_value() operations = {'+':operator.add, '-':operator.sub, '*':operator.mul, ‘/':operator.truediv} left = expression_tree.get_left_child() right = expression_tree.get_right_child() if left and right: return operations[token](evaluate(left), evaluate(right)) else: return token 27

107 - Trees What is that operator stuff? The operator module provides functions to add, subtract etc. We use a dictionary “operations” to connect the tokens “+”, “-”, “*” and “/” with the corresponding function. The line operations[token](evaluate(left), evaluate(right)) evokes the function on its parameters. 28

107 - Trees Tree Traversals Text book Section 6.7 With a binary tree we can recursively travel through all of the nodes (or traverse) in three standard ways. We can deal with the node first then deal with the left subtree, then the right subtree. This is a preorder traversal. We can deal with the left subtree, then with the node, then with the right subtree. This is an inorder traversal (and as we will see this keeps things in order). We can deal with the left subtree, then the right subtree and lastly the node itself. This is a postorder traversal (we used this to evaluate expression trees). 29

107 - Trees Code for printing tree traversals def print_preorder(tree): """Print the preorder traversal of the tree.""" if tree: print(tree.get_value(), end=' ') print_preorder(tree.get_left_child()) print_preorder(tree.get_right_child()) def print_postorder(tree): """Print the postorder traversal of the tree.""" if tree: print_postorder(tree.get_left_child()) print_postorder(tree.get_right_child()) print(tree.get_value(), end=' ') def print_inorder(tree): """Print the inorder traversal of the tree.""" if tree: print_inorder(tree.get_left_child()) print(tree.get_value(), end=' ') print_inorder(tree.get_right_child()) 30