Advanced Java Concepts Unit 5: Trees. Notes and Exercises

Similar documents
Advanced Java Concepts Unit 5: Trees. Notes and Exercises

March 20/2003 Jayakanth Srinivasan,

TREES. Trees - Introduction

Section 5.5. Left subtree The left subtree of a vertex V on a binary tree is the graph formed by the left child L of V, the descendents

Chapter 20: Binary Trees

Binary Trees, Binary Search Trees

a graph is a data structure made up of nodes in graph theory the links are normally called edges

Data Structures. Trees. By Dr. Mohammad Ali H. Eljinini. M.A. Eljinini, PhD

Principles of Computer Science

CE 221 Data Structures and Algorithms

Binary Trees and Huffman Encoding Binary Search Trees

CISC 235 Topic 3. General Trees, Binary Trees, Binary Search Trees

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

Binary Trees and Binary Search Trees

Introduction to Binary Trees

INF2220: algorithms and data structures Series 1

Binary Trees

Chapter 4 Trees. Theorem A graph G has a spanning tree if and only if G is connected.

Lecture Notes 16 - Trees CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson

Programming II (CS300)

CS350: Data Structures Tree Traversal

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

Associate Professor Dr. Raed Ibraheem Hamed

There are many other applications like constructing the expression tree from the postorder expression. I leave you with an idea as how to do it.

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

CSI33 Data Structures

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

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text)

CMPSCI 187: Programming With Data Structures. Lecture #26: Binary Search Trees David Mix Barrington 9 November 2012

CSE143 Summer 2008 Final Exam Part B KEY August 22, 2008

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

Garbage Collection: recycling unused memory

Discussion 2C Notes (Week 8, February 25) TA: Brian Choi Section Webpage:

tree nonlinear Examples

Partha Sarathi Mandal

Introduction to Computers and Programming. Concept Question

Tree Structures. A hierarchical data structure whose point of entry is the root node

Stacks, Queues and Hierarchical Collections

CSCI-401 Examlet #5. Name: Class: Date: True/False Indicate whether the sentence or statement is true or false.

Binary Trees. Examples:

Also, recursive methods are usually declared private, and require a public non-recursive method to initiate them.

Topic 14. The BinaryTree ADT

STUDENT LESSON AB30 Binary Search Trees

Tree Data Structures CSC 221

Week 2. TA Lab Consulting - See schedule (cs400 home pages) Peer Mentoring available - Friday 8am-12pm, 12:15-1:30pm in 1289CS

CSC148 Week 6. Larry Zhang

Lecture 23: Binary Search Trees

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

Computer Science 210 Data Structures Siena College Fall Topic Notes: Trees

Tree. A path is a connected sequence of edges. A tree topology is acyclic there is no loop.

Stacks, Queues and Hierarchical Collections. 2501ICT Logan

Data Structure Lecture#10: Binary Trees (Chapter 5) U Kang Seoul National University

IX. Binary Trees (Chapter 10)

BINARY TREES, THE SEARCH TREE ADT BINARY SEARCH TREES, RED BLACK TREES, TREE TRAVERSALS, B TREES WEEK - 6

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs

Chapter Contents. Trees. Tree Concepts. Hierarchical Organization. Hierarchical Organization. Hierarchical Organization.

Revision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted,

Section Summary. Introduction to Trees Rooted Trees Trees as Models Properties of Trees

Successor/Predecessor Rules in Binary Trees

7.1 Introduction. A (free) tree T is A simple graph such that for every pair of vertices v and w there is a unique path from v to w

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

Binary Trees. Height 1

Announcements. Midterm exam 2, Thursday, May 18. Today s topic: Binary trees (Ch. 8) Next topic: Priority queues and heaps. Break around 11:45am

Trees. Truong Tuan Anh CSE-HCMUT

A set of nodes (or vertices) with a single starting point

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

Data Structures and Algorithms

Trees, Binary Trees, and Binary Search Trees

Binary Search Trees 1

Data Structures and Algorithms for Engineers

An Introduction to Trees

ITI Introduction to Computing II

Upcoming ACM Events Linux Crash Course Date: Time: Location: Weekly Crack the Coding Interview Date:

CS102 Binary Search Trees

Binary Trees Fall 2018 Margaret Reid-Miller

Trees. Dr. Ronaldo Menezes Hugo Serrano Ronaldo Menezes, Florida Tech

syntax tree - * * * - * * * * * 2 1 * * 2 * (2 * 1) - (1 + 0)

First Semester - Question Bank Department of Computer Science Advanced Data Structures and Algorithms...

Binary Search Tree (2A) Young Won Lim 5/17/18

Trees. Estruturas de Dados / Programação 2 Árvores. Márcio Ribeiro twitter.com/marciomribeiro. Introduc)on. Hierarchical structure

ITI Introduction to Computing II

Recursion, Binary Trees, and Heaps February 18

INF2220: algorithms and data structures Series 1

The tree data structure. Trees COL 106. Amit Kumar Shweta Agrawal. Acknowledgement :Many slides are courtesy Douglas Harder, UWaterloo

Binary Tree. Binary tree terminology. Binary tree terminology Definition and Applications of Binary Trees

Cpt S 122 Data Structures. Data Structures Trees

Name Section Number. CS210 Exam #3 *** PLEASE TURN OFF ALL CELL PHONES*** Practice

CSE 230 Intermediate Programming in C and C++ Binary Tree

Trees. Q: Why study trees? A: Many advance ADTs are implemented using tree-based data structures.

Data Structure - Binary Tree 1 -

Trees. Linear vs. Branching CSE 143. Branching Structures in CS. What s in a Node? A Tree. [Chapter 10]

BINARY SEARCH TREES cs2420 Introduction to Algorithms and Data Structures Spring 2015

6-TREE. Tree: Directed Tree: A directed tree is an acyclic digraph which has one node called the root node

Building Java Programs

Chapter Summary. Introduction to Trees Applications of Trees Tree Traversal Spanning Trees Minimum Spanning Trees

Trees. Introduction & Terminology. February 05, 2018 Cinda Heeren / Geoffrey Tien 1

CS61B Lecture #20: Trees. Last modified: Wed Oct 12 12:49: CS61B: Lecture #20 1

CMSC 341. Binary Search Trees CMSC 341 BST

Advanced Tree Data Structures

Transcription:

dvanced Java Concepts Unit 5: Trees. Notes and Exercises Tree is a data structure like the figure shown below. We don t usually care about unordered trees but that s where we ll start. Later we will focus on ordered trees because they support efficient searching. Please read the following short discussion about where binary trees are used: http://stackoverflow.com/questions/210416/what-are-the-applications-of-binary-trees Vocabulary H Each node in a tree can have multiple successors and all items, except for the root, have exactly one predecessor. G Q node s predecessor is called its parent. node s successors are called its children. node that has no children is called a leaf. The line that connects a parent to its child is called an edge or branch. path is a sequence of edges that connect a node and one of its descendants. Path length refers to the number of edges in a path. The level of a node equals the length of the path connecting it to the root. Therefor the root is always at level zero. Note. pparently these definitions vary a little from source to source but these are the definitions that we will use. Questions. Use the above figure to answer the following questions. H The root is Name all the leaves in this tree: 2 Node is at level, N, The length of the path from Node to Node H is N E binary tree is a tree where each node has a maximum of two children, referred to as the left child and right child. We will only work with binary trees. binary tree is called a recursive structure because each subset is itself a binary tree, called the left or right subtree of the original tree. Page 1

Traversing a Tree. Traversal Method Definition ecursive Definition ample Tree B C Inorder left-root-right If root is not null: Traverse the left subtree inorder Visit the root Traverse the right subtree inorder Preorder root-left-right If root is not null: Visit the root Traverse the left subtree preorder Traverse the right subtree preorder Postorder left- right- root If root is not null: Traverse the left subtree postorder Traverse the right subtree postorder Visit the root Level root, level 1, order level 2, etc. Inorder traversal produces: BC Preorder traversal produces: BC Postorder traversal produces: BC Level order produces: BC Example. left subtree inorder root right subtree inorder Inorder traversal yields: W H X Y H X W Y root left subtree preorder right subtree preorder Preorder traversal yields: X H W Y left subtree postorder right subtree postorder Postorder traversal yields: W H Y X root root level 1 level 2 Level order traversal yields: X H W Y Page 2

Ex 1. What is the level of? What is the level of? What is the level of W? 0 1 1 2, F,,, W,, F, W, F,,, W,,, W, F, What is the length of the path from to? Inorder traversal yields Preorder traversal yields Postorder traversal yields Level order traversal yields F W Ex 2. What is the level of P? 1 W,, Z, E, P,,, W, E, Z, P W, Z, P, E,,,, W, E, Z, P What is the length of the path from to? Inorder traversal yields Preorder traversal yields Postorder traversal yields Level order traversal yields How many leaves are in this tree? W Z E P Ex. P B, F, G, H, P,,, T, W, Y, Z P, F, B, H, G,,, Y, T, W, Z B B, G, H, F,, W, T, Z, Y,, P P, F,, B, H,, Y, G, T, Z, W Inorder traversal yields Preorder traversal yields Postorder traversal yields Level order traversal yields F G H T Y Z Ex 4. W D, G, B,, H, E, I, C, F, B, D, G, C, E, H, I, F G, D, B, H, I, E, F, C,, B, C, D, E, F, G, H, I 4 Inorder traversal yields Preorder traversal yields Postorder traversal yields Level order traversal yields How many leaves are in this tree? D B G H E C I F Page

Practice-It! Do the traveral1, traversal2, and traversal problems under Binary Trees in CE 14. The remaining exercises in Binary Trees involve adding methods to the IntTree class. This class uses a nested class named IntTreeNode which has three instance variables (left, right, and data) that are accessible from within the IntTree class. Here is the solution for the size exercise: public int size(){ return size( overalloot ); private int size( IntTreeNode root ){ if ( root == null ) return 0; else return 1 + size( root.left ) + size( root.right ); Use the above solution as a model and solve the following problems. countleaves sum countleftnodes depthum doublepositives numempty height isfull printlevel writetree Binary Expression Tree binary expression tree consists of either a single root (containing an operand) or stores a mathematical expression according to this rule: The root contains an operator that will be applied to the results of evaluating the expressions in the left and right subtrees, each of which is a binary expression tree. Each of these trees is a binary expression tree. 4 1. What does a preorder traversal yield? 2. What does a postorder traversal yield?. What does an inorder traversal yield? 4. What is the value of this expression? (use any of the above expressions) 5. What does a preorder traversal yield? 6. What does a postorder traversal yield? 7. What does an inorder traversal yield?. What is the value of this expression? * 9 + 2 9 2 + * 9 * ( 2 + ) 45 9 * + 2 Page 4

9. What does a preorder traversal yield? 10. What does a postorder traversal yield? 11. What does an inorder traversal yield?. What is the value of this expression? * - + 4 2-4 2 + * ( - ) * ( 4 + 2 ) 0 * - + 4 2 Notice. preorder traversal yields the prefix form. postorder traversal yields the postfix form. n inorder traversal yields the infix form except that you might have to add parentheses. The level of the nodes indicates the precedence. The operation at the root will always be the last operation performed. Operations in the highest level nodes (which is the bottom) are performed first. The evaluation of a binary expression tree is a recursive process because each subtree is itself another binary expression tree. Binary earch Tree. In a binary search tree, the left child is always less than its parent. The right child is always greater than the parent. There should be no duplicates. ctually, depending on whose definition you use there may be duplicates. In this course there are never any duplicates. Here is an example of a binary search trees. 0 7-1 5 9 Because of the recursive nature of a tree, everything in the left subtree of a binary search tree is less than the root. nd everything in the right tree is greater than the root. For a binary search tree, an inorder traversal gets the nodes in ascending order from least to greatest. Page 5

dding a value to a BT is rather simple. Compare the new value to the root value. If the root is null, then the value becomes the root node. If the new value is less than the root value, then compare it to the left node and repeat the process. If the new value is greater than the root value, then compare it to the right node and repeat the process. ample Problem 1. Create a BT by adding these numbers, in order:,, 5, 9 tep 1. The first number becomes the root. tep 2. ince the is less than, it becomes the left node. tep. ince the 5 is less than, we move its left node. ince 5 is greater than the, the new node becomes the right child of the node. 5 9 tep 4. ince the 9 is greater the, it goes to the right. ample Problem 2. 5 The BT to the right results from adding the following numbers in order 5, 0, 9, 7,, -1, 0 5 9 Note that a different shape tree will result if the order of the numbers is changed. -1 7 Ex 5. Which of these trees are valid binary search trees? C Tree T T W Tree B Tree C W W T Page 6

Ex 6. Draw a binary search tree that consists of these numbers: 2, 6,, 14 (added in this order). 2 6 14 Ex 7. Draw a binary search tree that consists of these numbers: 6, 2,, -2, 5, 7, 14 (added in this order). 6 2-2 5 7 14 Ex. Draw a binary search tree that consists of these numbers: H, B,, N, C,, J (added in this order). B C H J N Ex 9. Draw a binary search tree that consists of the letters in: MNICUE (added in this order). C E I M N U Ex 10. Below is a binary search tree. If 15 is added to the tree, show where it would be placed. 2 2 45 1 22 2 17 Ex 11. < x < Ex. < x < 15 5 9 1 x 5 x 0 60 5 9 2 7 Page 7

To delete a node from a tree is a little more complicated. There are three cases to consider. In all cases you must first find the item to remove ND keep a reference to its parent. Case 1. The item to be removed has no children. olution. et the appropriate pointer in the parent (left or right child) to null. Case 2. The item to be removed has 1 child. olution. et the appropriate reference in the parent (of the node to be deleted) to the child. Example. uppose we want to remove the 21. 15 4 21 15 4 17 17 1 1 Case. The item to be removed has 2 children. (This is the tricky one.) olution. One approach is to (1) search for the smallest item in the item's right subtree. (2) replace the data to be removed with the data from the smallest item. () remove the smallest item from the right subtree (which will be easy because it will have (at most) one child. Example. uppose we want to remove the 7. 7 11 4 4 11 4 11 4 tep 1. Find the smallest value in the right subtree (11) 11 4 tep 2. eplace the 7 with the 11. 4 tep. emove the original 11. Ex 1. edraw this tree after the is deleted. 20 7 50 20 7 50 65 65 Page

Ex 14. edraw this tree after the 65 is deleted. 20 20 7 50 7 50 65 Ex 15. edraw this tree after the 20 is deleted. 20 7 50 7 50 65 65 Ex 16. edraw this tree after the 0 is deleted. 44 44 25 70 25 70 57 0 57 75 94 75 94 9 9 Page 9

Ex 17. edraw this tree after the 70 is deleted and then 44 is deleted. 44 25 70 57 75 0 94 9 57 25 75 0 94 9 Ex 1. Draw a binary search where the numbers have been added in this order:, 14, 44, 24 Then the 14 is deleted and then 14 is added to the tree again. 14 24 44 Ex 19. Draw a binary search where the numbers have been added in this order: 60, 50, 40, 0, 45 Then 60 is deleted, 56 is added, and 40 is deleted. 0 50 45 56 Ex 20. Draw a binary search where the numbers have been added in this order: 5, 70, 51, 66, 75, 1, 77 Then 70 is deleted and 5 is deleted. 66 51 75 77 1 Ex 21. dd these numbers in this order: 70, 2, 45, 5, 2, 7. Then remove the 70 and add 61. 7, 2, 45, 5, 61, 2 61, 5, 45, 2, 2, 7 2, 45, 5, 61, 7, 2 What does a preorder traversal yield? What does a postorder traversal yield? What does an inorder traversal yield? Ex 22. dd these numbers in this order: 5,, 9, 1, 7, 4, 6. Then remove the 9 and add. 5,, 1, 7, 6, 1,, 6,, 7, 5 1,, 5, 6, 7, What does a preorder traversal yield? What does a postorder traversal yield? What does an inorder traversal yield? Page 10

Implementation of a Binary earch Tree. Here s the first version our BT of trings. public class BT{ private Node root; public BT(){ root = null; public void add( tring str ){ Node node = new Node( str ); if ( root == null ) root = node; else add( root, node ); private void add( Node n, Node newnode ){ // precondition: n is not null int comparevalue = newnode.compareto( n ); if ( comparevalue == 0 ) // already in the tree return; // no duplicates allowed else if ( comparevalue < 0 && n.left == null ) n.left = newnode; else if ( comparevalue < 0 ) add( n.left, newnode ); else if ( comparevalue > 0 && n.right == null ) n.right = newnode; else add( n.right, newnode ); private class Node implements Comparable<Node> { private tring s; private Node left, right; private Node( tring s ){ if ( s == null ) throw new IllegalrgumentException( "What?!" ); this.s = s; left = null; right = null; public int compareto( Node n ){ return s.compareto( n.s ); public boolean equals( Node n ){ if ( n == null ) return false; return this.s.equals( n.s ); Page 11

Program Modification 1. dd and complete the following methods for the BT class. public void postorder(){ if ( root == null ) return; else postorder( root ); ystem.out.println(); private void postorder(node n ){ Complete this method. It should traverse and print out the contents of the tree in post-order. This can be done with 5 lines of code. Test this using the code below public class unbt{ public static void main( tring [] args ){ BT b1 = new BT(); b1.add( "M" ); b1.add( "Z" ); b1.add( "" ); b1.add( "C" ); b1.postorder(); // C Z M BT b2 = new BT(); b2.add( "Z" ); b2.add( "C" ); b2.add( "M" ); b2.add( "" ); b2.postorder(); // M C Z Program Modification 2. dd and complete the following methods for the BT class. public tring findmallest(){ This returns the least string in the tree (but does not delete it). You should write a private recursive helper method. If the root is null then return null. Test this using the code below BT b1 = new BT(); b1.add( "K" ); b1.add( "E" ); b1.add( "W" ); b1.add( "F" ); ystem.out.println( b1.findmallest() ); // E Page

Program Modification. Here s the big one. Write the remove method. public void remove( tring str ){ Delete the string from the tree following the guidelines discussed earlier. If the string is not in the tree then do nothing. This is not a simple method. t some point you will make a recursive call to a method. When you do, you will need to pass the string, the node you are checking, and the parent of the node you are checking. You may want to write a search method that searches the tree for str. Then if it finds it, then call a private helper method to delete that node. Use the following code to test your program. fter adding all the letters BT b1 = new BT(); b1.add( "M" ); b1.add( "G" ); b1.add( "" ); b1.add( "K" ); b1.add( "" ); b1.add( "" ); b1.add( "Z" ); b1.postorder(); // K G Z M G K M Z b1.remove("k"); b1.postorder(); // G Z M b1.remove("g"); b1.postorder(); b1.remove("m"); b1.postorder(); // Z M // Z Z b1.add( "P" ); b1.add( "X" ); b1.postorder(); // P X Z lso test your code with this: BT b2 = new BT(); b2.add( "" ); b2.add( "K" ); b2.add( "" ); b2.postorder(); // K b2.remove( "" ); b2.postorder(); // K P X Z Page 1