Chapter 4 Data Structures ADT Examples  Stack  Queue  Trees.

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

InOrder Traversal Algorithm // InOrder traversal algorithm inOrder(TreeNode n) { if (n != null) { inOrder(n.getLeft()); visit(n) inOrder(n.getRight());
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.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
1 CSCD 326 Data Structures I Stacks. 2 Data Type Stack Most basic property: last item in (most recently inserted) is first item out LIFO - last in first.
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 19 Binary.
Marc Smith and Jim Ten Eyck
Data Structures Using C++1 Chapter 11 Binary Trees.
1 Genericity Parameterizing by Type. 2 Generic Class One that is parameterized by type  Works when feature semantics is common to a set of types On object.
Trees Chapter 8. 2 Tree Terminology A tree consists of a collection of elements or nodes, organized hierarchically. The node at the top of a tree is called.
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.
Grade 12 Computer Studies HG
Tree. Basic characteristic Top node = root Left and right subtree Node 1 is a parent of node 2,5,6. –Node 2 is a parent of node.
CM0551 Exam Prep. What are an algorithm’s time and space complexity? (2 marks) Answer: The growth rate of the algorithm’s time requirement and the computer.
24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 1 Class 16 - Searching r Linear search r Binary search r Binary search trees.
Binary Trees Chapter Definition And Application Of Binary Trees Binary tree: a nonlinear linked list in which each node may point to 0, 1, or two.
© 2011 Pearson Addison-Wesley. All rights reserved 11 B-1 Chapter 11 (continued) Trees.
CMSC 341 Introduction to Trees. 8/3/2007 UMBC CMSC 341 TreeIntro 2 Tree ADT Tree definition  A tree is a set of nodes which may be empty  If not empty,
DATA STRUCTURES AND ALGORITHMS Lecture Notes 5 Prepared by İnanç TAHRALI.
Binary Trees 2 Overview Trees. Terminology. Traversal of Binary Trees. Expression Trees. Binary Search Trees.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
TREES Lecture 12 CS2110 – Fall Announcements  Prelim #1 is tonight!  Olin 155  A-L  5:30  M-Z  5:30  A4 will be posted today  Mid-semester.
1 Stacks and Queues Based on D.S. Malik, Java Programming: Program Design Including Data Structures.
Topic 19 Binary Search Trees "Yes. Shrubberies are my trade. I am a shrubber. My name is 'Roger the Shrubber'. I arrange, design, and sell shrubberies."
Stacks and Queues Based on D.S. Malik, Java Programming: Program Design Including Data Structures.
Slide 1 Linked Data Structures. Slide 2 Learning Objectives  Nodes and Linked Lists  Creating, searching  Linked List Applications  Stacks, queues.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use at Midwestern State University Chapter.
Copyright © 2002 Pearson Education, Inc. Slide 1.
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.
1/14/20161 BST Operations Data Structures Ananda Gunawardena.
Binary Search Tree. Tree  A nonlinear data structure consisting of nodes, each of which contains data and pointers to other nodes.  Each node has only.
ADT Binary Search Tree Ellen Walker CPSC 201 Data Structures Hiram College.
Binary Search Trees (BST)
CHAPTER 5 TREE CSEB324 DATA STRUCTURES & ALGORITHM.
Chapter 8 Binary Search Trees. Chapter 8: Binary Search Trees 8.1 – Trees 8.2 – The Logical Level 8.3 – The Application Level 8.4 – The Implementation.
Copyright © 2012 Pearson Education, Inc. Chapter 20: Binary Trees.
Data Abstraction and Problem Solving with JAVA Walls and Mirrors Frank M. Carrano and Janet J. Prichard © 2001 Addison Wesley Data Abstraction and Problem.
CMSC 341 Binary Search Trees. 8/3/2007 UMBC CMSC 341 BST 2 Binary Search Tree A Binary Search Tree is a Binary Tree in which, at every node v, the values.
2/11/ IT 179 Recursive Definition of Tree Structures 1.Empty is a tree; the root is null 2.A node points to a finite number of the roots of some.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 20: Binary Trees.
Search: Binary Search Trees Dr. Yingwu Zhu. Review: Linear Search Collection of data items to be searched is organized in a list x 1, x 2, … x n – Assume.
COSC 2P03 Week 21 Stacks – review A Last-In First-Out (LIFO) structure Basic Operations: –push : insert data item onto top of stack –pop : remove data.
“The desire for safety stands against every great and noble enterprise.” – Tacitus Thought for the Day.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 20: Binary Trees.
(c) University of Washington20-1 CSC 143 Java Trees.
Data Structure By Amee Trivedi.
Chapter 12 – Data Structures
Binary Tree ADT: Properties
Trees Chapter 11 (continued)
Stacks – review A Last-In First-Out (LIFO) structure Basic Operations:
Recursive Definition of Tree Structures
Trees Chapter 11 (continued)
Lecture No.13 Data Structures Dr. Sohail Aslam
Chapter 20: Binary Trees.
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.
Depict the Tree Structure in a picture
Stacks – review A Last-In First-Out (LIFO) structure Basic Operations:
Chapter 21: Binary Trees.
Trees.
General Trees & Binary Trees
Circular List removedNode General Case Single Node Case lastNode aNode
Stacks with Dynamic Memory
Pointers & Dynamic Data Structures
CSC 143 Java Trees.
Tree.
Presentation transcript:

Chapter 4 Data Structures ADT Examples  Stack  Queue  Trees

Data structures in Java  Java provides a set of data structures… well, we can implement a set of data structures using Java.  There is a major difference between C/C++ and Java –dynamic data structures (C/C++ uses pointers) –static data structures (no pointers, however this does not prevent us from implementing data structures in Java)

Stack Class  Stack (LIFO data structure) can be implemented as the following Class: class Stack { …. Stack() { … } boolean empty() { … } void push(Object o) { … } Object pop() { … } Object peek() { … } }  An application - check if balanced parentheses, e.g. (a+sin(x)-A[i-j])/(cos(x)+{p-q}/{m-n})

An Application - Balanced Parenthesis Checking class ParenMatcher { …. private boolean match(char c,char d) { switch(c) { case ‘(‘ : return (d==‘)’); case ‘[‘ : return (d==‘]’); case ‘{‘ : return (d==‘}’); default : return false; }

...Parenthesis Checking public void parenMatch() { Stack s = new Stack(); int n = inputString.length(); int i= 0; char c,d; while (i<n) { d=inputString.charAT(i); if (d==‘(‘ || d==‘[‘ || d==‘{‘) s.push(new Character(d)); else if (d==‘)‘ || d==‘]‘ || d==‘}‘) if (s.empty()){ output(“More right parenthesis than left”); return;} else {c = ((Character)s.pop()).charValue(); if (!match(c,d)){ output(“Mismatched parenthesis”); return;}} ++i;} }

Array Implementation (for Stack) class Stack { private int count, capacity, capacityIncr; private Object[] itemArray; public Stack() { count=0; capacity=10; capacityIncr=5; itemArray = new Object[capacity]; } itemArray countcapacity capacityIncr

Stack Methdos public boolean empty() {return (count==0); } public Object pop(){ if (count==0) return null; else {return itemArray[--count];} } public Object peek(){ if (count==0) { return null; } else {return itemArray[count-1];} }

More Methods public void push(Object ob) { if (count==capacity){ capacity += capacityIncr; Object[] tempArray = new Object[capacity]; for (int i=0; i<count; i++) {tempArray[i] = itemArray[i];} itemArray=tempArray; } itemArray[count++]=ob; }

Linked-List Implementation (for Stack) class StackNode { Object item; StackNode link; } itemlink An Object

Stack Class class Stack { private StackNode topNode; public Stack() { topNode=null; } public boolean empty() {return(topNode==null);} public Object pop() { if (topNode==null) { return null; } else { StackNode temp=topNode; topNode=topNode.link; return temp.item; }

More Methods public Object peek() { if (topNode==null) return null; else return topNode.item; } public void push(Object ob) { StackNode newNode = new StackNode(); newNode.item = ob; newNode.link = topNode; topNode = newNode; }

Queue Class  Stack (LIFO data structure) can be implemented as the following Class: class Stack { …. Queue() { … } ; boolean empty() { … }; void insert(Object o) { … };// at back Object remove() { … };// from fornt }  Useful for simulation, etc.  Queue on a Circular Track – Advance front & rear one, as follows: front=(front+1) % size; rear=(rear+1) % size; front rear A B C D E F G count 7

Circular Array Implementation (for Queue) class Stack { private int front,rear,count,capacity, capacityIncr; private Object[] itemArray; public Queue() { front=0; rear=0; count=0; capacity=10; capacityIncr=5; itemArray = new Object[capacity]; } public boolean empty() {return (count==0); } public Object remove() { if (count==0) { return null; } else {Object tempitem = itemArray[front]; front=(front+1) % capacity; count--; return tempitem;} }

More Methods public void insert(Object ob) { if (count==capacity){ capacity+=capacityIncr; Object[] tempArray = new Object[capacity];..copy to new array & assign to itemArray.. } itemArray[rear]=ob; rear=read+1 % capacity; count++; }

Trees  Trees are useful for organising complex data & for representing expressions. * fact if 5 > n root internal nodes leaves Level 0 Level 1 Level 2 Level 3

Binary Trees  A binary tree is either an empty tree, or a node whose left and right subtrees are binary trees. class TreeNode{ Object info; TreeNode left, right; TreeNode(Object ob, TreeNode l,r) {info=ob;left=l;right=r;} TreeNode(Object ob) {info=ob;left=null;right=null;} } data constructor

Creating a tree: * + / empty trees t2 t1 TreeNode t1=new TreeNode(“/”,new TreeNode(“6”),new TreeNode(“3”)); TreeNode t2=new TreeNode(“*”,new TreeNode(“8”),new TreeNode(“+”,t1,new TreeNode(“7”)));

Tree Traversals  There are three common ways of tree traversals  pre-order traversal  in-order traversal  post-order traversal

void preOrder(TreeNode t) { if (t!=null) { process(t.info); preOrder(t.left); preOrder(t.right); } void inOrder(TreeNode t) { if (t!=null) { inOrder(t.left); process(t.info); inOrder(t.right); } void postOrder(TreeNode t) { if (t!=null) { postOrder(t.left); postOrder(t.right); process(t.info); } preOrder(t2) * 8 + / inOrder(t2) 8 * 6 / post-Order(t2) / 7 + *

Data for Binary Search Tree class TreeNode{ CompareKey key; TreeNode left; TreeNode right; } class BinarySearchTree { private TreeNode rootNode; public BinarySearchTree() {TreeNode = null} …// methods static TreeNode find(TreeNode t, CompareKey k) {…} void insert(CompareKey k) {…} }  Node and BST declarations.

CompareKey Interface  For polymorphism, BST stores Objects. However their keys need to be comparable.  Hence, we should define an interface of the following. interface CompareKey { // if k1 & k2 are CompareKeys, then k1.compareTo(k2) // returns either // 0, +1, -1 according to k1==k2, k1>k2, or k1<k2 in the // ordering defined int compareTo(CompareKey value); }

IntegerKey class IntegerKey implements CompareKey{ private Integer key; … // additional data possible IntegerKey(Integer value) {key=value); IntegerKey(int value) {key=new Integer(value)); public int compareTo(CompareKey val){ int a = this.key; int b = ((IntegerKey)val).key; if (a.intvalue == b.intvalue) return 0; else return (a.intvalue < b.intvalue) ? -1 : +1 ; }

BST Method : Find a Node  To find a node in a BST, we have: static TreeNode find(TreeNode t, CompareKey k) { if (t==null) return null; else if ((result=k.compareTo(t.key))==0) return t; else if (result >0) return find(t.right,k); else return find(t.left,k); }

BST Method : Insert a Node  a recursive insertion function: void insert(CompareKey k) { rootNode = insertKey(rootNode,k); } private static TreeNode insertKey(TreeNode t,CompareKey k) { if (t==null) { TreeNode n = new TreeNode(); n.key = k; return n; } else if (k.compareTo(t.key)>0 { t.right = insertKey(t.right,k); return t; } else { t.left = insertKey(t.left,k); return t; }