1 CS 163 Data Structures Chapter 9 Building, Printing Binary Trees Herbert G. Mayer, PSU Status 5/21/2015.

Slides:



Advertisements
Similar presentations
1 CS 410 Mastery in Programming Chapter 8 Printing Binary Trees Herbert G. Mayer, PSU CS Status 5/22/2013.
Advertisements

1 CS 162 Introduction to Computer Science Chapter 9 Binary Trees Herbert G. Mayer, PSU Status 11/23/2014.
Senem Kumova Metin Spring2009 BINARY TREES && TREE TRAVERSALS Chapter 10 in A Book on C.
TREES Chapter 6. Trees - Introduction  All previous data organizations we've studied are linear—each element can have only one predecessor and successor.
1 CS 162 Introduction to Computer Science Chapter 8 Pointers Herbert G. Mayer, PSU Status 11/20/2014.
1 Tree Traversal Section 9.3 Longin Jan Latecki Temple University Based on slides by Paul Tymann, Andrew Watkins, and J. van Helden.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
Kymberly Fergusson CSE1303 Part A Data Structures and Algorithms Summer Semester 2003 Lecture A12 – Binary Trees.
1 Nell Dale Chapter 9 Trees Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
1 CS 410 Mastery in Programming Chapter 8 Printing Binary Trees Herbert G. Mayer, PSU CS status 7/30/2011.
Tree Traversal. Traversal Algorithms preorder inorder postorder.
Lec 15 April 9 Topics: l binary Trees l expression trees Binary Search Trees (Chapter 5 of text)
Kymberly Fergusson CSE1303 Part A Data Structures and Algorithms Summer Semester 2003 Lecture A12 – Binary Trees.
1 CS 410 Mastery in Programming Chapter 7 Hints for: Symbolic Differentiation Herbert G. Mayer, PSU CS status 7/26/2011.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Stacks.
1 CS308 Data Structures An application of binary trees: Binary Expression Trees.
CS21, Tia Newhall Binary Search Trees (BST) 1.Hierarchical data structure with a single pointer to root node 2.Each node has at most two child nodes (a.
Data Structures Using C++1 Chapter 11 Binary Trees.
Binary Trees. Node structure Data A data field and two pointers, left and right.
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.
(c) University of Washington20d-1 CSC 143 Java Applications of Trees.
12-CRS-0106 REVISED 8 FEB 2013 CSG2A3 ALGORITMA dan STRUKTUR DATA.
Trees EENG212 Algorithms and Data Structures. Trees Outline  Introduction to Trees  Binary Trees: Basic Definitions  Traversing Binary Trees  Node.
Trees.ppt1 Introduction Many data structures are linear –unique first component –unique last component –other components have unique predecessor and successor.
Searching: Binary Trees and Hash Tables CHAPTER 12 6/4/15 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,
Data Structures : Project 5 Data Structures Project 5 – Expression Trees and Code Generation.
Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.
1 Trees A tree is a data structure used to represent different kinds of data and help solve a number of algorithmic problems Game trees (i.e., chess ),
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.
Tree Data Structures.
1 Chapter 10 Trees. 2 Definition of Tree A tree is a set of linked nodes, such that there is one and only one path from a unique node (called the root.
Data Structures and Algorithm Analysis Trees Lecturer: Jing Liu Homepage:
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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 2)
Slide 1 Linked Data Structures. Slide 2 Learning Objectives  Nodes and Linked Lists  Creating, searching  Linked List Applications  Stacks, queues.
Copyright © 2002 Pearson Education, Inc. Slide 1.
CE 221 Data Structures and Algorithms Chapter 4: Trees (Binary) Text: Read Weiss, §4.1 – 4.2 1Izmir University of Economics.
1 Storing Hierarchical Information Lists, Stacks, and Queues represent linear sequences Data often contain hierarchical relationships that cannot be expressed.
Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.
Binary Search Trees (BST)
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.
CHAPTER 5 TREE CSEB324 DATA STRUCTURES & ALGORITHM.
CHP-3 STACKS.
18-1 Chapter 18 Binary Trees Data Structures and Design in Java © Rick Mercer.
ADTS, GRAMMARS, PARSING, TREE TRAVERSALS Lecture 13 CS2110 – Spring
1 CS 201 Computer Systems Programming Chapter 7 “Printing Binary Trees” Herbert G. Mayer, PSU CS Status 7/9/2014.
Chapter 12 – Data Structures
CS 163 Data Structures Chapter 10 Symbolic Differentiation
CS 201 Data Structures and Algorithms
Herbert G. Mayer, PSU CS status 7/29/2013
Paul Tymann and Andrew Watkins
PART II STACK APPLICATIONS
CS 201 Computer Systems Programming Chapter 7 “Printing Binary Trees”
TREE DATA STRUCTURE Data Structure 21-Sep-18 Tree
Binary Trees, Binary Search Trees
Chapter 20: Binary Trees.
Chapter 21: Binary Trees.
Paul Tymann, Andrew Watkins,
ASTs, Grammars, Parsing, Tree traversals
Section 9.3 by Andrew Watkins
Binary Trees, Binary Search Trees
Paul Tymann, Andrew Watkins,
CSC 143 Java Applications of Trees.
Trees, part 2 Lecture 13 CS2110 – Spring 2019
CS 201 Computer Systems Programming Chapter 7 “Printing Binary Trees”
Binary Trees, Binary Search Trees
Presentation transcript:

1 CS 163 Data Structures Chapter 9 Building, Printing Binary Trees Herbert G. Mayer, PSU Status 5/21/2015

2 Syllabus Arithmetic Expressions and Trees Arithmetic Expressions and Trees Infix Without Parentheses Infix Without Parentheses Infix With Parentheses Infix With Parentheses Postfix Without Parentheses Postfix Without Parentheses Prefix Without Parentheses Prefix Without Parentheses Interesting Examples Interesting Examples Use of Postfix Use of Postfix Building Trees Building Trees Tree of Ints Tree of Ints

3 Arithmetic Expressions and Trees Three typical notations for dyadic operations: Three typical notations for dyadic operations: Infix notation: write as the first the left operand, reading left-to- right, then list the dyadic operator, finally list the right operand Infix notation: write as the first the left operand, reading left-to- right, then list the dyadic operator, finally list the right operand For CPU: Order will not work for code emission, as the CPU needs both operands for processing the operator For humans: requires parentheses for proper operator precedence Note exception: programming language APL Postfix notation: write left operand first, then list the right operand, finally the operator Postfix notation: write left operand first, then list the right operand, finally the operator This order will work for code emission, as operator has both operands available at processing time Needs no parentheses, and still obeys operator precedence Postfix notation AKA Polish Postfix, after Jan Łukasiewicz, 1920 Prefix notation: First list the operator, next the first (left) operand, finally the second (right) operand Prefix notation: First list the operator, next the first (left) operand, finally the second (right) operand

4 Arithmetic Expressions and Trees a + x ^ c + a^ xc Infix:( a + ( x ^ c ) ) Postfix:a x c ^ + Prefix:+ a ^ x c ^ stands for exponentiation, with highest precedence: higher than * or /

5 Arithmetic Expressions and Trees ( x – a ) / b / - b ax Infix:( ( x – a ) ) / b Postfix:x a – b / Prefix:/ – x a b / stands for division operator, with higher precedence than, say, –

6 Arithmetic Expressions and Trees a ^ ( b – c ) / d / ^ d -a Infix:( ( a ^ ( b – c ) ) / d ) Postfix:a b c - ^ d / Prefix:/ ^ a – b c d bc

7 Data Structure to Print Trees // node has class: literal, identifier, or operator. // Parenthesized expressions have been reduced: no ( ) typedef enum { Literal, Identifier, Operator } NodeClass; typedef struct NodeType * NodePtr; // forward // actual node structure; using the forward pointers typedef struct NodeType { NodeClass Class; // 3 classes. Not C++ ‘class’ NodeClass Class; // 3 classes. Not C++ ‘class’ char Symbol; // stores ident or small literal char Symbol; // stores ident or small literal int LitVal; // if Class == Literal: its value int LitVal; // if Class == Literal: its value NodePtr Left; // left subtree NodePtr Left; // left subtree NodePtr Right; // right subtree NodePtr Right; // right subtree } s_node_tp;

8 Infix Without Parentheses // Print in infix notation without parentheses ( ) void Print_No_Paren( NodePtr Root ) { // Print_No_Paren if ( Root ) { Print_No_Paren ( Root->Left ); if ( Root->Class == Literal ) { printf( "%d", Root->LitVal ); }else{ printf( "%c", Root->Symbol ); } //end if Print_No_Paren ( Root->Right ); } //end if } //end Print_No_Paren Input: ( a + x ) / b prints as: a + x / b  misleading

9 Infix With Parentheses // Print in infix notation with parentheses ( and ) void Print_Infix( NodePtr Root ) { // Print_Infix if ( Root ) { if ( Root->Class == Operator ) { printf( "(" ); } //end if Print_Infix( Root->Left ); if ( Root->Class == Literal ) { printf( "%d", Root->LitVal ); }else{ printf( "%c", Root->Symbol ); } //end if Print_Infix( Root->Right ); if ( Root->Class == Operator ) { printf( ")" ); } //end if } //end Print_Infix Input: ( a + x ) / b prints as: ( ( a + x ) / b ) -- OK

10 Postfix Without Parentheses // Print in Polish Postfix notation, no parentheses void Print_Postfix( NodePtr Root ) { // Print_Postfix if ( Root ) { Print_Postfix( Root->Left ); Print_Postfix( Root->Right ); if ( Root->Class == Literal ) { printf( "%d", Root->LitVal ); }else{ printf( "%c", Root->Symbol ); } //end if } //end Print_Postfix Input: a ^ ( b – c ) / d prints as: a b c - ^ d / -- OK

11 Prefix Without Parentheses // Prefix: operator executes when 2 operands found void Print_Prefix( NodePtr Root ) { // Print_Prefix if ( Root ) { if ( Root->Class == Literal ) { printf( "%d", Root->LitVal ); }else{ printf( "%c", Root->Symbol ); } //end if Print_Prefix ( Root->Left ); Print_Prefix ( Root->Right ); } //end if } //end Print_Prefix Input: ( a + x ) / b prints as: / + a x b -- OK

12 Interesting Examples Input 1:a + b * c ^ ( x – 2 * d ) / ( e – f ) Infix:( a + ( ( b * ( c ^ ( x – ( 2 * d ) ) ) ) / ( e – f ) ) ) Postfix:a b c x 2 d * - ^ * e f - / + Prefix:+ a / * b ^ c – x * 2 d – e f Input 2:4 / x ^ ( k – l / m ) * 8 * x - & 9 + n Infix:( ( ( ( ( 4 / ( x ^ ( k - ( l / m ) ) ) ) * 8 ) * x ) - ( & 9 ) ) + n ) Postfix:4 x k l m / - ^ / 8 * x * 9 & - n + Prefix:+ - * * / 4 ^ x – k / l m 8 x & 9 n

13 Use of Postfix Postfix, AKA Polish Postfix notation is a natural for code generation, targeted for stack machines Postfix, AKA Polish Postfix notation is a natural for code generation, targeted for stack machines Operands are needed first: Two for dyadic, or one for monadic operations Operands are needed first: Two for dyadic, or one for monadic operations Once generated and available on stack, stack machine can execute the next operation Once generated and available on stack, stack machine can execute the next operation Easy for compiler writer, natural for stack machine Easy for compiler writer, natural for stack machine Stack poor for execution, as all references are through memory: top of stack Stack poor for execution, as all references are through memory: top of stack Even a GPR architecture needs both operands available somewhere (in regs) to execute operator Even a GPR architecture needs both operands available somewhere (in regs) to execute operator

14 Building Trees Now you understand: Trees constitute inherently recursive data structures Now you understand: Trees constitute inherently recursive data structures You learned how to traverse them, and in various orders You learned how to traverse them, and in various orders Now we learn how to build them Now we learn how to build them Initially trees may be unbalanced Initially trees may be unbalanced Worst case, they may be so-called left- spine (or right-spine) trees, i.e. no different from linear lists, but more costly to process Worst case, they may be so-called left- spine (or right-spine) trees, i.e. no different from linear lists, but more costly to process

15 Building Trees Let tree nodes be simple int data structures Let tree nodes be simple int data structures Each node holds an integer value named info Each node holds an integer value named info Info numbers don’t need to be unique Info numbers don’t need to be unique Provide data from input files, or hard-coded Provide data from input files, or hard-coded Since node numbers may be repeated, each node includes a count Since node numbers may be repeated, each node includes a count Let the left and right subtrees be named smaller and greater, alluding to info ordering Let the left and right subtrees be named smaller and greater, alluding to info ordering Thus we have sufficient information to define the node data structure in C++ Thus we have sufficient information to define the node data structure in C++

16 Building Trees, Node Type typedef struct node_tp * node_ptr_tp; typedef struct node_tp { int info;// the node! int info;// the node! int count;// how many? int count;// how many? node_ptr_tp smaller;// left subtree node_ptr_tp smaller;// left subtree node_ptr_tp greater; // and right node_ptr_tp greater; // and right } str_node_tp; node_ptr_tp root = NULL; // key Datum

17 Allocate Node Off Heap //use C malloc() or C++ new operator node_ptr_tp make_node( int info ) { // make_node node_ptr_tp node= new str_node_tp; if( node ) { node->info= info; node->info= info; node->smaller= NULL; node->smaller= NULL; node->greater= NULL; node->greater= NULL; node->count= 1; node->count= 1;}else{ error( ”...” ); } //end if return node; return node; } //end make_node

18 Tree of Ints Tree is pointed to by root, initially nil Tree is pointed to by root, initially nil Type of root is pointer to node, in C++ node_ptr_tp Type of root is pointer to node, in C++ node_ptr_tp When the next info element is searched in an empty tree, i.e. if root == NULL, new node is inserted, count set to 1, root points to that new node, and root is returned When the next info element is searched in an empty tree, i.e. if root == NULL, new node is inserted, count set to 1, root points to that new node, and root is returned Done by node_ptr_tp function insert() Done by node_ptr_tp function insert() Else, since tree is not empty, the current info is compared; if yields a match, count is incremented and root to that existing node is returned Else, since tree is not empty, the current info is compared; if yields a match, count is incremented and root to that existing node is returned

19 Tree of Ints Else, if there is no match, traverse the left or the right subtree, depending on whether root->greater or root->smaller Else, if there is no match, traverse the left or the right subtree, depending on whether root->greater or root->smaller I.e., whether info > root->info I.e., whether info > root->info Or whether info info Or whether info info And recurse! And recurse!

20 Tree of Ints // Given “info”, insert in tree: “root” node_ptr_tp insert( node_ptr_tp & root, int info ) { // insert if ( NULL == root ) {// why in this order? root = make_node( info ); }else if( info > root->info ) { }else if( info > root->info ) { root->greater = insert( root->greater, info ); root->greater = insert( root->greater, info ); }else if( info info ) { }else if( info info ) { root->smaller = insert( root->smaller, info ); root->smaller = insert( root->smaller, info ); }else{ }else{ root->count++; root->count++; } //end if } //end if return root; return root; } //end insert

21 Traverse Tree of Ints In-order When the complete tree is constructed, it is pointed to by global root, of node_ptr_tp When the complete tree is constructed, it is pointed to by global root, of node_ptr_tp To traverse, we can use pre-order, post- order or in-order To traverse, we can use pre-order, post- order or in-order In-order handles left subtree first In-order handles left subtree first Then looks at node Then looks at node And finally traverses right subtree And finally traverses right subtree

22 Traverse Tree of Ints In-order // traverse binary tree, root, in in-order void in_order( node_ptr_tp root ) { // in_order if ( root ) { if ( root ) { in_order( root->smaller ); in_order( root->smaller ); printf( "%d(%d) ", root->info, printf( "%d(%d) ", root->info, root->count ); in_order( root->greater ); in_order( root->greater ); } //end if } //end if } //end in_order

23 Sample Tree Traversal Let’s build a binary tree of ints, pointed to by root Let’s build a binary tree of ints, pointed to by root The input sequence we consider is given here: The input sequence we consider is given here: We build the tree as shown above We build the tree as shown above Tracking the count of each integer value, by giving this in parentheses Tracking the count of each integer value, by giving this in parentheses E.g. -11(3) would mean: integer value -11 is in the tree and did occur 3 times in the input provided E.g. -11(3) would mean: integer value -11 is in the tree and did occur 3 times in the input provided

24 Sample Tree Traversal Hard-coded input of data to build tree: Hard-coded input of data to build tree: // enter some arbitrary ints void get_data( void ) { // get_data for ( int node = -5; node < 20; node += 3 ) { for ( int node = -5; node < 20; node += 3 ) { root = insert( root, node ); root = insert( root, node ); root = insert( root, node - 9 ); root = insert( root, node - 9 ); // printf( "%d %d ", node, node - 9 ); // printf( "%d %d ", node, node - 9 ); } //end for } //end for } //end get_data

25 Sample Tree Traversal int main() { // main printf( "Entering fixed list of: " ); get_data( ); get_data( ); printf( "\n in order : " ); printf( "\n in order : " ); in_order( root ); in_order( root ); printf( "\n" ); printf( "\n" ); return 0; return 0; } //end main

26 Sample Output in order : -14(1) -11(1) -8(1) -5(2) -2(2) 1(2) 4(2) 7(2) 10(2) 13(1) 16(1) 19(1)

27 References Łukasiewicz: Łukasiewicz: