Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose.

Slides:



Advertisements
Similar presentations
Chapter 7. Binary Search Trees
Advertisements

Binary Trees Chapter 6. Linked Lists Suck By now you realize that the title to this slide is true… By now you realize that the title to this slide is.
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.
Binary Trees Terminology A graph G = is a collection of nodes and edges. An edge (v 1,v 2 ) is a pair of vertices that are directly connected. A path,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 26 Binary Search Trees.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L12 (Chapter 20) Lists, Stacks,
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
1 General Trees & Binary Trees CSC Trees Previous data structures (e.g. lists, stacks, queues) have a linear structure. Linear structures represent.
Marc Smith and Jim Ten Eyck
Binary Search Trees Chapter 7 Objectives
Chapter 08 Binary Trees and Binary Search Trees © John Urrutia 2013, All Rights Reserved.
Version TCSS 342, Winter 2006 Lecture Notes Trees Binary Trees Binary Search Trees.
CS 146: Data Structures and Algorithms June 18 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
By : Budi Arifitama Pertemuan ke Objectives Upon completion you will be able to: Create and implement binary search trees Understand the operation.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Trees.
Data Structures Arrays both single and multiple dimensions Stacks Queues Trees Linked Lists.
1 Chapter 25 Trees Iterators Heaps Priority Queues.
Tree.
Review Binary Tree Binary Tree Representation Array Representation Link List Representation Operations on Binary Trees Traversing Binary Trees Pre-Order.
Advanced Algorithms Analysis and Design Lecture 8 (Continue Lecture 7…..) Elementry Data Structures By Engr Huma Ayub Vine.
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.
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.
AITI Lecture 20 Trees, Binary Search Trees Adapted from MIT Course 1.00 Spring 2003 Lecture 28 and Tutorial Note 10 (Teachers: Please do not erase the.
S EARCHING AND T REES COMP1927 Computing 15s1 Sedgewick Chapters 5, 12.
© 2011 Pearson Addison-Wesley. All rights reserved 11 B-1 Chapter 11 (continued) Trees.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
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 ),
Chapter 19 Implementing Trees and Priority Queues Fundamentals of Java.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 20 Lists, Stacks,
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
1 Chapter 17 Object-Oriented Data Structures. 2 Objectives F To describe what a data structure is (§17.1). F To explain the limitations of arrays (§17.1).
Binary Search Trees Binary Search Trees (BST)  the tree from the previous slide is a special kind of binary tree called a binary.
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.
Topic 15 The Binary Search Tree ADT Binary Search Tree A binary search tree (BST) is a binary tree with an ordering property of its elements, such.
Binary Search Trees Nilanjan Banerjee. 2 Goal of today’s lecture Learn about Binary Search Trees Discuss the first midterm.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 25 Trees, Iterators,
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 19 Binary Search Trees.
1 Chapter 7 Objectives Upon completion you will be able to: Create and implement binary search trees Understand the operation of the binary search tree.
Binary Search Trees (BST)
COSC 2P03 Week 21 Tree Traversals – reminder Breadth-first traversal: starting from root, visit all nodes on each level in turn, from left to right Depth-first.
1 Joe Meehean. A A B B D D I I C C E E X X A A B B D D I I C C E E X X  Terminology each circle is a node pointers are edges topmost node is the root.
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.
Chapter 10 Trees © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
18-1 Chapter 18 Binary Trees Data Structures and Design in Java © Rick Mercer.
Chapter 11. Chapter Summary  Introduction to trees (11.1)  Application of trees (11.2)  Tree traversal (11.3)  Spanning trees (11.4)
Lecture 12 CS 202. FXML JavaFX also offers a way to code UI controls in XML, while writing the event handlers and other application logic in Java. The.
Binary Search Trees Chapter 7 Objectives
Topic 2: binary Trees COMP2003J: Data Structures and Algorithms 2
Chapter 25 Binary Search Trees
Trees Chapter 11 (continued)
Trees Chapter 11 (continued)
The Tree Data Structure
Week 6 - Wednesday CS221.
Binary Search Tree (BST)
Trees.
Chapter 17 Object-Oriented Data Structures
Chapter 20: Binary Trees.
Chapter 22 : Binary Trees, AVL Trees, and Priority Queues
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Chapter 21: Binary Trees.
General Trees & Binary Trees
Lecture 12 CS203 1.
Lecture 8: Iterators, Trees
General Trees & Binary Trees
CSC 143 Java Trees.
Trees.
Data Structures Using C++ 2E
Chapter 11 Trees © 2011 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

Lecture 10 1

Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose to give back to the profession make many projects available for free This allows you to use functionality you lack the time or expertise to code It also requires a slightly different set of skills than those you use when you write your own code from scratch. Programming becomes an exercise in hacking other people's ideas so they fit together to get the results you want. You will seldom find that the programmers of the libraries you use thought their work out the same way you would have. Quality control is nonexistent and malware is probably sometimes spread this way! You will learn several other ways to get libraries and integrate them into your projects, but here is the simple way

Using Libraries Find the website for the library you want and download it. If you have the choice to get the bytecode alone or with the source included, get the version that includes the source You will usually need to unzip or untar the library. The free software 7-Zip can untar, but avoid installing the junkware that comes with 7-Zip. The result will include one or more.jar files. Often there is also documentation, tutorials, and other material as well. Right click on the project name and choose "Build Path/Configure Build Path", then "Add External JARs", then find the Jar you need to add. The library should now appear under "Referenced Libraries" in your project

Using Libraries

JFreeChart JFreeChart is a very widely used free library for creating graphs in Java. If the demo below is not enough, google JFreeChart bar graph (or whatever else you need to look up) for tutorials and discussions, especially on StackOverflow.com Download JFreeChart from JFreeChart is not yet easy to use with JavaFX, so the demo below uses Swing When you add the JFreeChart jar to the build path for your project, you will also have to add JCommon, which you will get in the download package.

Using Libraries package charts; import java.awt.Color; import java.awt.Dimension; import java.awt.GradientPaint; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RefineryUtilities; public class BarChartDemo extends ApplicationFrame { public BarChartDemo(final String title) { super(title); final CategoryDataset dataset = createDataset(); final JFreeChart chart = createChart(dataset); final ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new Dimension(750, 405)); setContentPane(chartPanel); }

Using Libraries private CategoryDataset createDataset() { // row keys... final String series1 = "Monster"; // column keys... final String category1 = "Godzilla"; final String category2 = "Jersey Devil"; final String category3 = "Dracula"; final String category4 = "Dick Cheney"; // create the dataset... final DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(115.5, series1, category1); dataset.addValue(8.5, series1, category2); dataset.addValue(12.0, series1, category3); dataset.addValue(9.0, series1, category4); return dataset; } private JFreeChart createChart(final CategoryDataset dataset) { // create the chart... final JFreeChart chart = ChartFactory.createBarChart("Shoe Size Chart", // chart title "Name", // domain axis label "Shoe Size", // range axis label dataset, // data PlotOrientation.VERTICAL, // orientation false, // don't include legend true, // tooltips? false // URLs? );

Using Libraries // set the background color for the chart... chart.setBackgroundPaint(Color.white); // get a reference to the plot for further customisation... final CategoryPlot plot = chart.getCategoryPlot(); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); // set the range axis to display integers only... final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); final BarRenderer renderer = (BarRenderer) plot.getRenderer(); // set up gradient paints for series... final GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, Color.blue, 0.0f, 0.0f, Color.lightGray); renderer.setSeriesPaint(0, gp0); return chart; } public static void main(final String[] args) { final BarChartDemo demo = new BarChartDemo("Bar Chart Demo"); demo.pack(); RefineryUtilities.centerFrameOnScreen(demo); demo.setVisible(true); }

9 PDFBox PDFBox is a library for extracting text from pdfs Get the "Standalone binary" at As is typical for this type of library, it is not well documented. If the demo below is not enough, check Eclipse's context- sensitive help or look for comments on StackOverflow.

10 PDFBox package pdftograph; import java.io.File; import java.io.IOException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.util.PDFTextStripper; public class PDFBoxDemo { public void readPDF(File f) { PDDocument p; PDFTextStripper strip; String text = null; try { p = PDDocument.load(f); strip = new PDFTextStripper(); text = strip.getText(p); } catch (IOException e) { e.printStackTrace(); } System.out.println(text); } public static void main(String[] args){ PDFBoxDemo reader = new PDFBoxDemo(); reader.readPDF(new File("Dracula_T.pdf")); }

Using Libraries See why it's so important to adhere to conventions for things like method name capitalization?

12 Binary Trees A list, stack, or queue is a linear structure that consists of a sequence of elements. A binary tree is a hierarchical structure. It is either empty or consists of an element, called the root, and two distinct binary trees, called the left subtree and right subtree.

13 Binary Tree Terms The root of left (right) subtree of a node is called a left (right) child of the node. A node without children is called a leaf. A special type of binary tree called a binary search tree is often useful. A binary search tree (with no duplicate elements) has this property: – for every node in the tree, the value of any node in its left subtree is less than the value of the node and the value of any node in its right subtree is greater than the value of the node. Note that this requires a way to order the elements, so in Java we usually either build trees of Comparables or use Comparators This section is concerned with binary search trees, which, as the name suggests, allow you to easily implement binary search.

14 Representing Binary Trees A binary tree can be represented using a set of linked nodes. Each node contains a value and two links named left and right that reference the left child and right child, respectively, as shown in Figure class TreeNode { E element; TreeNode left; TreeNode right; public TreeNode(E o) { element = o; }

15 Searching an Element in a Binary Tree public boolean search(E element) { TreeNode current = root; // Start from the root while (current != null) if (element < current.element) { current = current.left; // Go left } else if (element > current.element) { current = current.right; // Go right } else // Element matches current.element return true; // Element is found return false; // Element is not in the tree }

16 Inserting an Element to a Binary Tree If a binary tree is empty, create a root node with the new element. Otherwise, locate the parent node for the new element node. If the new element is less than the parent element, the node for the new element becomes the left child of the parent. If the new element is greater than the parent element, the node for the new element becomes the right child of the parent.

17 Inserting an Element to a Binary Tree if (root == null) root = new TreeNode(element); else { // Locate the parent node current = root; while (current != null) if (element value < the value in current.element) { parent = current; current = current.left; } else if (element value > the value in current.element) { parent = current; current = current.right; } else return false; // Duplicate node not inserted // Create the new node and attach it to the parent node if (element < parent.element) parent.left = new TreeNode(elemenet); else parent.right = new TreeNode(elemenet); return true; // Element inserted } Insert 101 into the following tree.

18 Trace Inserting 101 into the following tree, cont. Several steps omitted…

19 Trace Inserting 101 into the following tree, cont. if (root == null) root = new TreeNode(element); else { // Locate the parent node current = root; while (current != null) if (element value < the value in current.element) { parent = current; current = current.left; } else if (element value > the value in current.element) { parent = current; current = current.right; } else return false; // Duplicate node not inserted // Create the new node and attach it to the parent node if (element < parent.element) parent.left = new TreeNode(elemenet); else parent.right = new TreeNode(elemenet); return true; // Element inserted } Insert 101 into the following tree. 101 < 107 true

20 Trace Inserting 101 into the following tree, cont. if (root == null) root = new TreeNode(element); else { // Locate the parent node current = root; while (current != null) if (element value < the value in current.element) { parent = current; current = current.left; } else if (element value > the value in current.element) { parent = current; current = current.right; } else return false; // Duplicate node not inserted // Create the new node and attach it to the parent node if (element < parent.element) parent.left = new TreeNode(elemenet); else parent.right = new TreeNode(elemenet); return true; // Element inserted } Insert 101 into the following tree. current is null now

21 Trace Inserting 101 into the following tree, cont. if (root == null) root = new TreeNode(element); else { // Locate the parent node current = root; while (current != null) if (element value < the value in current.element) { parent = current; current = current.left; } else if (element value > the value in current.element) { parent = current; current = current.right; } else return false; // Duplicate node not inserted // Create the new node and attach it to the parent node if (element < parent.element) parent.left = new TreeNode(elemenet); else parent.right = new TreeNode(elemenet); return true; // Element inserted } Insert 101 into the following tree. 101 < 107 true

22 Trace Inserting 101 into the following tree, cont. if (root == null) root = new TreeNode(element); else { // Locate the parent node current = root; while (current != null) if (element value < the value in current.element) { parent = current; current = current.left; } else if (element value > the value in current.element) { parent = current; current = current.right; } else return false; // Duplicate node not inserted // Create the new node and attach it to the parent node if (element < parent.element) parent.left = new TreeNode(elemenet); else parent.right = new TreeNode(elemenet); return true; // Element inserted } Insert 101 into the following tree. 101 < 107 true

23 Trace Inserting 101 into the following tree, cont. if (root == null) root = new TreeNode(element); else { // Locate the parent node current = root; while (current != null) if (element value < the value in current.element) { parent = current; current = current.left; } else if (element value > the value in current.element) { parent = current; current = current.right; } else return false; // Duplicate node not inserted // Create the new node and attach it to the parent node if (element < parent.element) parent.left = new TreeNode(elemenet); else parent.right = new TreeNode(elemenet); return true; // Element inserted } Insert 101 into the following tree. 101 < 107 true

24 Inserting 59 into the Tree if (root == null) root = new TreeNode(element); else { // Locate the parent node current = root; while (current != null) if (element value < the value in current.element) { parent = current; current = current.left; } else if (element value > the value in current.element) { parent = current; current = current.right; } else return false; // Duplicate node not inserted // Create the new node and attach it to the parent node if (element < parent.element) parent.left = new TreeNode(elemenet); else parent.right = new TreeNode(elemenet); return true; // Element inserted }

25 Tree Traversal Tree traversal is the process of visiting each node in the tree exactly once. There are several ways to traverse a tree. This section presents inorder, preorder, postorder, depth-first, and breadth-first traversals. Inorder traversal visits the left subtree of the current node first recursively, then the current node itself, and finally the right subtree of the current node recursively. Postorder traversal visits the left subtree of the current node first, then the right subtree of the current node, and finally the current node itself. Preorder traversal visits the current node first, then the left subtree of the current node recursively, and finally the right subtree of the current node recursively.

26 Tree Traversal, cont. Breadth-first traversal visits the nodes level by level. First visit the root, then all children of the root from left to right, then grandchildren of the root from left to right, and so on. For example, in the tree below, the inorder is The postorder is The preorder is The breadth-first traversal is

27 Trees The Java Collections Framework does not contain a general-purpose tree implementation. There is one in Swing that is designed for use with GUI components. Liang's Introduction To Java Programming contains general-purpose Tree code.

28 The Tree Interface The Tree interface defines common operations for trees, and the AbstractTree class partially implements Tree.

29 The BinaryTree Class Let’s define the binary tree class, named BinaryTree with A concrete BinaryTree class can be defined to extend AbstractTree. BST

30 Example: Using Binary Trees See the code from Liang linked from the course web page

31 Tree After Insertions Inorder: Adam, Daniel George, Jones, Michael, Peter, Tom Postorder: Daniel Adam, Jones, Peter, Tom, Michael, George Preorder: George, Adam, Daniel, Michael, Jones, Tom, Peter

32 Deleting Elements in a Binary Search Tree To delete an element from a binary tree: Locate the node that contains the element and also its parent node. Let current point to the node that contains the element in the binary tree and parent point to the parent of the current node. The current node may be a left child or a right child of the parent node. There are two cases to consider

33 Deleting Elements in a Binary Search Tree Case 1: The current node does not have a left child, as shown in this figure (a). Simply connect the parent with the right child, if any, of the current node, as shown in this figure (b).

34 Deleting Elements in a Binary Search Tree For example, to delete node 10 in Figure 27.9a. Connect the parent of node 10 with the right child of node 10, as shown in Figure 27.9b.

35 Deleting Elements in a Binary Search Tree Case 2: The current node has a left child. The left subtree contains some node that contains the greatest value in the subtree. All the other nodes in the subtree will be left of it in the newly configured tree All subtrees of this rightmost value will be to the right of the rightmost node’s parent

36 Deleting Elements in a Binary Search Tree Case 2: The current node has a left child. Let rightMost point to the node that contains the largest element in the left subtree of the current node and parentOfRightMost point to the parent node of the rightMost node, as shown in Figure 27.10a. – Note that the rightMost node cannot have a right child, but may have a left child. Replace the element value in the current node with the one in the rightMost node Connect the parentOfRightMost node with the left child of the rightMost node Delete the rightMost node, as shown in Figure 27.10b.

37 Deleting Elements in a Binary Search Tree Case 2 diagram

38 Deleting Elements in a Binary Search Tree Case 2 example, delete 20 All other nodes in the left subtree will be left of this one

39 Examples If we promoted Adam to root, we would also have to move Daniel to the right subtree

40 Examples

41 Examples

42 binary tree time complexity The time complexity for the inorder, preorder, and postorder is O(n), since each node is traversed only once. The time complexity for search, insertion and deletion is the height of the tree. In the worst case, the height of the tree is n. In the best case it is log n. We want our trees to be balanced, so that we get the O(log n) search behavior. That's coming up in the next lecture.