CS 241 Data Organization Binary Trees

Similar documents
Read: Kernighan & Ritchie

CP2 Revision. theme: dynamic datatypes & data structures

Linked Lists in C and C++

Cpt S 122 Data Structures. Course Review Midterm Exam # 1

TI2725-C, C programming lab, course

Chapter 20: Binary Trees

CS 322 Operating Systems Practice Midterm Questions

Crit-bit Trees. Adam Langley (Version )

Crit-bit Trees. Adam Langley (Version )

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

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

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

C Data Structures Stacks. Stack. push Adds a new node to the top of the stack

CS61, Fall 2012 Section 2 Notes

Binary Search Tree 1.0. Generated by Doxygen Mon Jun :12:39

CS24 Week 8 Lecture 1

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

3. Priority Queues. ADT Stack : LIFO. ADT Queue : FIFO. ADT Priority Queue : pick the element with the lowest (or highest) priority.

Trees. A tree is a directed graph with the property

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

CS 241 Data Organization Pointers and Arrays

Algorithms and Data Structures

Binary Trees (and Big O notation)

Linked-List Basic Examples. A linked-list is Linear collection of self-referential class objects, called nodes Connected by pointer links

BBM 201 DATA STRUCTURES

1. Stack overflow & underflow 2. Implementation: partially filled array & linked list 3. Applications: reverse string, backtracking

Recursion, Trees and Tree Traversal. Module CE System Programming & Computer Control Systems

Cpt S 122 Data Structures. Data Structures

DAY 3. CS3600, Northeastern University. Alan Mislove

Intermediate Programming, Spring 2017*

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

Welcome! COMP s1. Programming Fundamentals

Binary Trees

ENEE 150: Intermediate Programming Concepts for Engineers Spring 2018 Handout #27. Midterm #2 Review

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

DC104 DATA STRUCTURE JUNE Q.2 a. If you are using C language to implement the heterogeneous linked list, what pointer type will you use?

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

o Code, executable, and process o Main memory vs. virtual memory

C Introduction. Comparison w/ Java, Memory Model, and Pointers

ECE264 Spring 2013 Final Exam, April 30, 2013

Binghamton University. CS-211 Fall Dynamic Memory

CS 237 Meeting 19 10/24/12

Solution for Data Structure


ECE264 Fall 2013 Exam 3, November 20, 2013

1) What is the primary purpose of template functions? 2) Suppose bag is a template class, what is the syntax for declaring a bag b of integers?

Stacks, Queues and Hierarchical Collections

Systems Programming. 05. Structures & Trees. Alexander Holupirek

Data Structures. Outline. Introduction Linked Lists Stacks Queues Trees Deitel & Associates, Inc. All rights reserved.

Graphs & Digraphs Tuesday, November 06, 2007

CT11 (ALCCS) DATA STRUCTURE THROUGH C JUN 2015

Week 5, continued. This is CS50. Harvard University. Fall Cheng Gong

Short Notes of CS201

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

Binary Trees. Height 1

Chapter 6. Data Structure. /* start contains the address of the first node */ start = &elephant1; print_elephants( start ); return EXIT_SUCCESS;

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9

Fall, 2015 Prof. Jungkeun Park

Low-Level C Programming. Memory map Pointers Arrays Structures

CS 11 C track: lecture 5

CSE 333 Midterm Exam 2/14/14

CS 222: Pointers and Manual Memory Management

CS201 - Introduction to Programming Glossary By

Programming Assignment #4 Binary Trees in C++

Homework 3 CS161 Computer Security, Fall 2008 Assigned 10/07/08 Due 10/13/08

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

Dynamic Data Structures (II)

Stacks, Queues and Hierarchical Collections. 2501ICT Logan

ITI Introduction to Computing II

Data Abstractions. National Chiao Tung University Chun-Jen Tsai 05/23/2012

Please submit your request directly to Noha Sinno

Largest Online Community of VU Students

COMP26120: Linked List in C (2018/19) Lucas Cordeiro

CSC 1600 Memory Layout for Unix Processes"

ECE 15B COMPUTER ORGANIZATION

Programming II (CS300)

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

Programming Abstractions

CPSC 213. Introduction to Computer Systems. Winter Session 2017, Term 2. Unit 1c Jan 24, 26, 29, 31, and Feb 2

ITI Introduction to Computing II

Sample Problems for Quiz # 3

A6-R3: DATA STRUCTURE THROUGH C LANGUAGE

Trees (part 2) CSE 2320 Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington

speller.c dictionary contains valid words, one per line 1. calls load on the dictionary file

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

Programming Tips for CS758/858

Recursion. Data and File Structures Laboratory. DFS Lab (ISI) Recursion 1 / 27

NET/JRF-COMPUTER SCIENCE & APPLICATIONS. Time: 01 : 00 Hour Date : M.M. : 50

Chapter 9. Priority Queue

Programs in memory. The layout of memory is roughly:

(6-1) Basics of a Queue. Instructor - Andrew S. O Fallon CptS 122 (September 26, 2018) Washington State University

ECE 2035 Programming HW/SW Systems Spring problems, 5 pages Exam Three 8 April Your Name (please print clearly)

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

We have the pointers reference the next node in an inorder traversal; called threads

Programming II (CS300)

Programming and Data Structure Solved. MCQs- Part 2

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

CS61B Lecture #20: Trees. Last modified: Mon Oct 8 21:21: CS61B: Lecture #20 1

12 Abstract Data Types

Transcription:

CS 241 Data Organization Binary Trees Brooke Chenoweth University of New Mexico Fall 2017

Binary Tree: Kernighan and Ritchie 6.5 Read a file and count the occurrences of each word. now is the time for all good men to come to the aid of their party now is the for men of time all good party their to aid come

Adding Node to Ordered Tree If a node were added with the word hello, where would it be placed? now is the for men of time all good party their to aid come

Adding Node to Ordered Tree If a node were added with the word hello, where would it be placed? now is the for men of time all good party their to aid come hello

Binary Tree: tnode The structure, tnode, is used for each node of the binary tree. struct tnode { char * word ; int count ; struct tnode * left ; struct tnode * right ; }; This is called a self-referential structure since it contains pointers to other tnodes. An instance of this struct allocates space for a pointer to a char array, two pointers to other tnodes and an int. On a 64-bit address machine, this is a total of 16 bytes.

Binary Tree: talloc (NOT a Library Function) 1. Allocate memory for a tree node. 2. In this binary tree, nodes are added to leaves. Thus, initialize the node s children to NULL. 3. Call strcopymalloc to allocate space for the word and to copy it from the input buffer into the allocated space. struct tnode * talloc ( char * newword ) { struct tnode * node = malloc ( sizeof ( struct tnode )); node - > word = strcopymalloc ( newword ); node -> left = NULL ; node -> right = NULL ; node -> count = 1; return node ;

Binary Tree: strcopymalloc 1. Allocated memory for a copy of newword. 2. Copy each character from newword into the allocated block. 3. Return a pointer to the start of the allocated block. char * strcopymalloc ( char * source ) { char * sink ; sink = malloc ( strlen ( source )+1); if ( sink!= NULL ) strcpy ( sink, source ); return sink ; }

Binary Tree: Memory Leaks In Kernighan and Ritchie s binary tree, memory is allocated and never freed! MEMORY LEAK WARNING: DO NOT free a node until: Its children have been freed, or pointers to its children have been saved somewhere else. Its word has been freed. struct tnode * root ; root = talloc (" Memory "); root -> right = talloc (" Leak "); root -> left = talloc (" Bad "); free ( root ); /* Leaves " unreachable " memory. */

Binary Tree: freesubtree Recursive function that frees all allocated memory in a subtree. 1 void freesubtree ( struct tnode * node ) 2 { 3 if ( node == NULL ) return ; 4 freesubtree (node -> left ); 5 freesubtree (node -> right ); 6 free (node -> word ); 7 free ( node ); 8 } Any references to node (such as would be in node s parent) MUST NOT BE USED AFTER calling this. Best practice is to set such references to NULL. Is this done here? If not, could it be done here? If so, between which lines and with what code?

Binary Tree: Simple Test Case This main() demonstrates usage and offers a simple test of creating, setting, printing, and freeing tnode. void main ( void ) { /* Can you tell I just stole Joel s code here? */ struct tnode * root ; root = talloc (" joel "); root -> left = talloc (" cool "); root -> right = talloc (" inspirational "); printf (" node : %s (L )=%s, (R )=% s\n", root ->word, root ->left ->word, root -> right -> word ); freesubtree ( root ); root = NULL ; /* " Best practice " */ /* (no effect on valgrind ) */ }

Binary Tree: No Leaks Are Possible Using valgrind results in something like the following: node: joel (L)=cool, (R)=inspirational ==24066== HEAP SUMMARY: ==24066== in use at exit: 0 bytes in 0 blocks ==24066== total heap usage: 6 allocs, 6 frees, 120 bytes allocated ==24066== ==24066== All heap blocks were freed -- no leaks are possible

Tree Traversal Depth First Explore as far as possible along each branch before backtracking Pre-order Root, left subtree, right subtree In-order Left subtree, root, right subtree Post-order Left subtree, right subtree, root Breadth First Visit every node on a level before going to lower level. (Also known as level-order)

Tree Traversal Example now is the for men of time all good party their to aid come

Tree Traversal Pre-order now is the for men of time all good party their to aid come Root, then children: now is for all aid come good men the of party time their to

Tree Traversal In-order now is the for men of time all good party their to aid come Left, root, right: aid all come for good is men now of party the their time to

Tree Traversal Post-order now is the for men of time all good party their to aid come Children, then root: aid come all good for men is party of their to time the now

Tree Traversal Breadth-first now is the for men of time all good party their to aid come One level at a time: now is the for men of time all good party their to aid come

Tree Traversal Code void treeprint ( struct tnode * node ) { if( node!= NULL ) { treeprint (node -> left ); printf ("%4d %s\n", node -> count, node -> word ); treeprint (node -> right ); } } What sort of traversal happens here? How could we traverse the tree in a different order?

Breadth-first Traversal Algorithm 1. Create a queue to hold tree nodes 2. Add root node to the queue 3. While queue is not empty: Remove node from queue and visit it. Add node s children to queue. A queue is a FIFO structure. How might we implement it? A stack is a LIFO structure. What would happen if we replaced the queue with a stack?