CSC 143 Java Applications of Trees.

Slides:



Advertisements
Similar presentations
Binary Trees CSC 220. Your Observations (so far data structures) Array –Unordered Add, delete, search –Ordered Linked List –??
Advertisements

Expression Trees What is an Expression tree? Expression tree implementation Why expression trees? Evaluating an expression tree (pseudo code) Prefix, Infix,
Prefix, Postfix, Infix Notation
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
CS 171: Introduction to Computer Science II
Topic 15 Implementing and Using Stacks
Trees Chapter Chapter Contents Tree Concepts Hierarchical Organizations Tree Terminology Traversals of a Tree Traversals of a Binary Tree Traversals.
Lec 15 April 9 Topics: l binary Trees l expression trees Binary Search Trees (Chapter 5 of text)
Unit 11a 1 Unit 11: Data Structures & Complexity H We discuss in this unit Graphs and trees Binary search trees Hashing functions Recursive sorting: quicksort,
Transforming Infix to Postfix
Topic 15 Implementing and Using Stacks
Fundamentals of Python: From First Programs Through Data Structures
The Stack and Queue Types Lecture 10 Hartmut Kaiser
Binary Trees. Node structure Data A data field and two pointers, left and right.
Chapter Chapter Summary Introduction to Trees Applications of Trees (not currently included in overheads) Tree Traversal Spanning Trees Minimum.
Review Binary Tree Binary Tree Representation Array Representation Link List Representation Operations on Binary Trees Traversing Binary Trees Pre-Order.
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.
Data Structures Lecture : Stacks (Infix, Postfix and Prefix Expressions) Azhar Maqsood NUST Institute of Information Technology (NIIT)
CSC 205 Programming II Postfix Expressions. Recap: Stack Stack features Orderly linear structure Access from one side only – top item Stack operations.
Searching. Motivation Find parts for a system Find an address for name Find a criminal –fingerprint/DNA match Locate all employees in a dept. based on.
(c) University of Washington20d-1 CSC 143 Java Applications of Trees.
Trees.ppt1 Introduction Many data structures are linear –unique first component –unique last component –other components have unique predecessor and successor.
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.
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.
Binary Trees Definition A binary tree is: (i) empty, or (ii) a node whose left and right children are binary trees typedef struct Node Node; struct Node.
Starting at Binary Trees
Binary Search Tree Traversal Methods. How are they different from Binary Trees?  In computer science, a binary tree is a tree data structure in which.
CSC 143 Trees [Chapter 10].
Week 7 - Friday.  What did we talk about last time?  Trees in general  Binary search trees.
Binary Search Trees (BST)
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 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.
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.
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.
Prefix, Postfix, Infix Notation. Infix Notation  To add A, B, we write A+B  To multiply A, B, we write A*B  The operators ('+' and '*') go in between.
Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving data LIFO (Last In First Out) structure.
353 3/30/98 CSE 143 Trees [Sections , 13.6,13.8]
CC 215 DATA STRUCTURES MORE ABOUT STACK APPLICATIONS Dr. Manal Helal - Fall 2014 Lecture 6 AASTMT Engineering and Technology College 1.
Applications of Stack Maitrayee Mukerji. Stacks Last In First Out (LIFO List) ◦ FILO? Insertions and Deletions from the same end called the Top Push(),
(c) University of Washington20-1 CSC 143 Java Trees.
DS.T.1 Trees Chapter 4 Overview Tree Concepts Traversals Binary Trees Binary Search Trees AVL Trees Splay Trees B-Trees.
Stacks Access is allowed only at one point of the structure, normally termed the top of the stack access to the most recently added item only Operations.
CS Data Structures Chapter 6 Stacks Mehmet H Gunes
CS 201 Data Structures and Algorithms
COMP 53 – Week Fourteen Trees.
COMPSCI 107 Computer Science Fundamentals
Podcast Ch17a Title: Expression Trees
Stack application: postponing data usage
PART II STACK APPLICATIONS
i206: Lecture 13: Recursion, continued Trees
TREE DATA STRUCTURE Data Structure 21-Sep-18 Tree
Binary Trees, Binary Search Trees
CS212: Data Structures and Algorithms
Stacks Chapter 5 Adapted from Pearson Education, Inc.
ADTs, Grammars, Parsing, Tree traversals
Section 9.3 by Andrew Watkins
CE 221 Data Structures and Algorithms
Data Structures and Algorithm Analysis Trees
Binary Trees, Binary Search Trees
Queue Applications Lecture 31 Mon, Apr 9, 2007.
CE 221 Data Structures and Algorithms
Topic 15 Implementing and Using Stacks
CSC 143 Java Trees.
Stack.
Queue Applications Lecture 31 Tue, Apr 11, 2006.
Applications of Stacks and Queues
CO4301 – Advanced Games Development Week 3 Parsing Continued
Binary Trees, Binary Search Trees
Presentation transcript:

CSC 143 Java Applications of Trees

Overview Applications of traversals Syntax trees Expression trees Postfix expression evaluation Infix expression conversion and evaluation

Traversals (Review) Preorder traversal: Postorder traversal: “Visit” the (current) node first i.e., do what ever processing is to be done Then, (recursively) do preorder traversal on its children, left to right Postorder traversal: First, (recursively) do postorder traversals of children, left to right Visit the node itself last Inorder traversal: (Recursively) do inorder traversal of left child Then visit the (current) node Then (recursively) do inorder traversal of right child Footnote: pre- and postorder make sense for all trees; inorder only for binary trees This section on pre/in/post order traversal was distracting from the main flow of building sets out of binary search trees. I would cut it next time.

Two Traversals for Printing public void printInOrder(BTreeNode t) { if (t != null) { printInOrder(t.left); system.out.println(t.data + “ “); printInOrder(t.right); } public void printPreOrder(BTreeNode t) { if (t != null) { system.out.println(t.data + “ “); printPreOrder(t.left); printPreOrder(t.right); }

Analysis of Tree Traversal How many recursive calls? Two for every node in tree (plus one initial call); O(N) in total for N nodes How much time per call? Depends on complexity O(V) of the visit For printing and many other types of traversal, visit is O(1)time Multiply to get total O(N)*O(V) = O(N*V) Does tree shape matter? Answer: No

Syntax and Expression Trees Computer programs have a hierarchical structure All statements have a fixed form Statements can be ordered and nested almost arbitrarily (nested if-then-else) Can use a structure known as a syntax tree to represent programs Trees capture hierarchical structure Wi99: Skipped this. Out of time.

A Syntax Tree Consider the Java statement: if ( a == b + 1 ) x = y; else ... statement if ( expression ) statement else statement equality expression ; ... expression expression LHS = expression == var var + const var var a b 1 x y

Syntax Trees An entire .java file can be viewed as a tree Compilers build syntax trees when compiling programs Can apply simple rules to check program for syntax errors Easier for compiler to translate and optimize than text file Process of building a syntax tree is called parsing

Binary Expression Trees A binary expression tree is a syntax tree used to represent meaning of a mathematical expression Normal mathematical operators like +, -, *, / Structure of tree defines result Easy to evaluate expressions from their binary expression tree (as we shall see)

Example 5 * 3 + (9 - 1) / 4 - 1 - + 1 / * - 4 5 3 9 1

Infix, Prefix, Postfix Expressions 5 * 3 Infix: binary operators are written between operands Postfix: operator after the operands Prefix: operator before the operands

Expression Tree Magic Traverse in postorder to get postfix notation! 5 3 * 9 1 - 4 / + 1 - Traverse in preorder to get prefix notation - + * 5 3 / - 9 1 4 1 Traverse in inorder to get infix notation 5 * 3 + 9 - 1 / 4 - 1 Note that infix operator precedence may be wrong! Correction: add parentheses at every step (((5*3) + ((9 - 1) / 4)) - 1)

More on Postfix 3 4 5 * - means same as (3 (4 5 *) -) infix: 3 - (4 * 5) Parentheses aren’t needed! When you see an operator: both operands must already be available. Stop and apply the operator, then go on Precedence is implicit Do the operators in the order found, period! Practice converting and evaluating: 1 2 + 7 * 2 % (3 + (5 / 3) * 6) - 4

Why Postfix? Does not require parentheses! Some calculators make you type in that way Easy to process by a program simple and efficient algorithm

Postfix Evaluation Algorithm Create an empty stack Will hold tokens Read in the next “token” (operator or data) If data, push it on the data stack If (binary) operator: call it “op” Pop off the most recent data (B) and next most recent (A) from the stack Perform the operation R = A op B Push R on the stack Continue with the next token When finished, the answer is the stack top. Simple, but works like magic!

Check Your Understanding According to the algorithm, 3 5 - means 3 - 5 ? Or 5 - 3 ? Answer 3 - 5 If data stack is ever empty or has only one piece of data when data is needed for an operation: Then the original expression was bad Why? Give an example: try 5 2 3 + / * If the data stack is not empty after the last token has been processed and the stack popped: Why? Give an example 5 2 3 4 1 + / *

Example: 3 4 5 - * Draw the stack at each step! Read 3. Push it (because it’s data) Read 4. Push it. Read 5. Push it. Read -. Pop 5, pop 4, perform 4 - 5. Push -1 Read *. Pop -1, pop 3, perform 3 * -1. Push -3. No more tokens. Final answer: pop the -3. note that stack is now empty

Algorithm: converting in- to post- Create an empty stack to hold operators Main loop: Read a token If operand, output it immediately If ‘(‘, push the '(' on stack If operator hold it aside temporarily if stack top is an op of >= precedence: pop and output repeat until ‘(‘ is on top or stack is empty push the new operator If ‘)’, pop and output until ‘(‘ has been popped Repeat until end of input Pop and output rest of stack

Magic Trick Suppose you had a bunch of numbers, and inserted them all into an initially empty BST. Then suppose you traversed the tree in-order. The nodes would be visited in order of their values. In other words, the numbers would come out sorted! Try it! This algorithm is called TreeSort

Tree Sort O(N log N) most of the time Time to build the tree, plus time to traverse When is it not O(N log N)? Answer: the tree is not balanced Trivial to program if you already have a binary search tree class Note: not an "in-place" sort The original tree is left in as-is, plus there is a new sorted list of equal size Is this good or bad? Is this true or not true of other sorts we know?

Preview of data structure class: Balanced Search Trees Cost of basic binary search operations Dependent on tree height O(log N) for N nodes if tree is balanced O(N) if tree is very unbalanced Can we ensure tree is always balanced? Yes: insert and delete can be modified to keep the tree pretty well balanced Several algorithms and data structures exist Details are complicated Results in O(log N) “find” operations, even in worst case