SlideShare ist ein Scribd-Unternehmen logo
1 von 16
Downloaden Sie, um offline zu lesen
UNIT II - JAVA DATA STRUCTURES
Lists
Linear Structures
Arrays
Stack
Queue
Linked List
Ordered & Unordered Structures
Order Structure
Un Ordered Structure
Sorting
Trees
Binary Tree
Example of a binary tree
Operations
Implementations
Binary Search Tree (BST)
.
Lists
Collections API Revisit?
List Abstract Data Type (ADT)
• A list a collection of items in which the items have a position
• We keep “to-do” lists, shop with a grocery list, and invite a list of friends to a party
• Types of Lists
– Ordered Lists - (implements Comparable Interface)
• An ordered list is kept in order based on characteristics of the elements in the list, e.g.
alphabetical order for names
– Unordered Lists
• They are stored in an order that is externally controlled by how and when the elements are
added to the list
– Indexed Lists
Topics Discussed in URL:
● List Implementations
● Adding and Accessing Elements
● Removing Elements
● Generic Lists
A List represents a data structure which allows to dynamically add, access and remove objects of the same type. Adding objects to the
list is usually done via the add() method. The get(int i) method allows to retrieve the element at position i. Remove objects from the
list is usually done via the remove(int i) method which removes the element at position i.
Below is a sample program that explains the following:
● Custom List Implementation (using Arrays) which allows Adding, Accessing & Removing Elements
● Test Application that uses the above Customized List
MyList.java
package list;
import java.util.Arrays;
import java.util.Iterator;
/**
* Created by user on 2/15/14.
*/
public class MyList<E> {
private int size = 0;
private static final int DEFAULT_CAPACITY = 10;
private Object elements[];
public MyList() {
elements = new Object[DEFAULT_CAPACITY];
}
public void add(E e) {
if (size == elements.length) {
ensureCapa();
}
elements[size++] = e;
}
private void ensureCapa() {
int newSize = elements.length * 2;
elements = Arrays.copyOf(elements, newSize);
}
@SuppressWarnings("unchecked")
public E get(int i) {
if (i >= size || i < 0) {
throw new IndexOutOfBoundsException("Index: " + i + ", Size " + i);
}
return (E) elements[i];
}
public E remove(int i) {
if (i >= size || i < 0) {
throw new IndexOutOfBoundsException("Index: " + i + ", Size " + i);
}
size++;
E oldValue = (E) elements[i];
int numMoved = size - i - 1;
if (numMoved > 0)
System.arraycopy(elements, i + 1, elements, i, numMoved);
elements[--size] = null;
return oldValue;
}
@Override
public String toString() {
String temp = new String();
temp = "[";
for (int i = 0; i < elements.length; i++) {
if (elements[i] != null)
temp = temp + " "+ (E) elements[i] ;
}
temp = temp + "]";
return temp;
}
}
The following show contains a small test for the data structure. I use in the first test the MyList implementation and in the second test
the standard Java List implementation.
MyMainListTest.java
package list;
import com.sun.org.apache.xpath.internal.SourceTree;
import java.util.ArrayList;
import java.util.List;
/**
* Created by user on 2/15/14.
*/
public class MyMainListTest {
public static void main(String[] args) {
MyMainListTest myMainListTest = new MyMainListTest();
System.out.println("Testing MyList");
try {
myMainListTest.testMyList();
} catch (Exception e) {
System.out.println("MyList " + e);
}
System.out.println("Testing StandardList");
try {
myMainListTest.testStandardList();
} catch (Exception e) {
System.out.println("StandardList " + e);
}
}
public void testMyList() {
MyList<Integer> list = new MyList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(3);
list.add(4);
list.add(2);
list.add(3);
list.add(3);
list.add(4);
list.add(2);
list.add(3);
list.add(3);
list.add(4);
System.out.println(list);
//Remove element on 4th Index.
list.remove(4);
System.out.println(list);
System.out.println(list.get(1));
System.out.println(list.get(6));
System.out.println(list.get(20));//Throws IndexOutOfBoundsException
System.out.println(list.get(-1));//Throws IndexOutOfBoundsException
}
public void testStandardList() {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(3);
list.add(4);
list.add(2);
list.add(3);
list.add(3);
list.add(4);
list.add(2);
list.add(3);
list.add(3);
list.add(4);
System.out.println(list);
//Remove element on 4th Index.
list.remove(4);
System.out.println(list);
System.out.println(list.get(1));
System.out.println(list.get(6));
System.out.println(list.get(20));//Throws IndexOutOfBoundsException
System.out.println(list.get(-1));//Throws IndexOutOfBoundsException
}
}
Linear Structures
Arrays
Arrays are special data types that let us store specified number of variables from the same type using one variable
name.
An array is a sequence of data item of homogeneous value(same type).
Why Arrays?
Imagine the situation that you need to store 20 names of students as strings and 20 integers as marks, then you need to
define 40 variables, and this is clearly very hard and not practical, in such case you need to use arrays.
Arrays are indexed data types.
As Figure shows, the size of an array is fixed, we will refer to array maximum size as array length , it is also clear that
indices of an array are zero-based, that is, they start from 0 to length – 1;for example, the array shown in Figure has a
length of 10 (stores up to 10 elements), and the last index is 9
Arrays are of two types:
1. One-dimensional arrays
2. Multidimensional arrays
One-Dimensional Arrays
● Declaration
● Initialization (Construction)
● Accessing Elements (Read / Write)
Multidimensional Arrays (Arrays of Arrays)
● Declaration
● Initialization (Construction)
● Accessing Elements (Read / Write)
http://www.tutorialspoint.com/java/util/arraylist_get.htm
Employee.java
public class Employee implements Comparable {
int EmpID;
String Ename;
double Sal;
static int i;
public Employee() {
EmpID = i++;
Ename = "dont know";
Sal = 0.0;
}
public Employee(String ename, double sal) {
EmpID = i++;
Ename = ename;
Sal = sal;
}
public String toString() {
return "EmpID " + EmpID + "n" + "Ename " + Ename + "n" + "Sal" + Sal;
}
public int compareTo(Object o1) {
if (this.Sal == ((Employee) o1).Sal)
return 0;
else if ((this.Sal) > ((Employee) o1).Sal)
return 1;
else
return -1;
}
}
ComparableDemo.java
import java.util.*;
public class ComparableDemo{
public static void main(String[] args) {
List ts1 = new ArrayList();
ts1.add(new Employee ("Tom",40000.00));
ts1.add(new Employee ("Harry",20000.00));
ts1.add(new Employee ("Maggie",50000.00));
ts1.add(new Employee ("Chris",70000.00));
Collections.sort(ts1);
Iterator itr = ts1.iterator();
while(itr.hasNext()){
Object element = itr.next();
System.out.println(element + "n");
}
}
}
Output:
EmpID 1
Ename Harry
Sal20000.0
EmpID 0
Ename Tom
Sal40000.0
EmpID 2
Ename Maggie
Sal50000.0
EmpID 3
Ename Chris
Sal70000.0
http://math.hws.edu/javanotes/c7/index.html
http://math.hws.edu/javanotes/c7/s3.html
http://math.hws.edu/javanotes/c7/s5.html
Stack
Stack Implementation using Arrays
http://www.vogella.com/tutorials/JavaDatastructures/article.html
http://www.youtube.com/watch?v=sFVxsglODoo
http://www.studytonight.com/data-structures/stack-data-structure
http://tutorials.jenkov.com/java-collections/stack.html
http://math.hws.edu/javanotes/c9/s3.html
Queue
Queue Implementation using Arrays
http://www.youtube.com/watch?v=okr-XE8yTO8
http://www.studytonight.com/data-structures/queue-data-structure
http://tutorials.jenkov.com/java-collections/queue.html
http://math.hws.edu/javanotes/c9/s3.html
Linked List
- Insert at Head
- Insert at Last (Append)
- Insert Middle Element
- Insert After Element
- Insert Before Element
- Delete Head
- Delete Last Element
- Delete Middle Element
http://www.cs.cmu.edu/~adamchik/15-121/lectures/Linked%20Lists/linked%20lists.html
http://www.idevelopment.info/data/Programming/data_structures/java/LinkedList/LinkedList.shtml
http://math.hws.edu/javanotes/c9/s2.html
http://www.tutorialspoint.com/java/java_linkedlist_class.htm
Ordered & Unordered Structures
Order Structure
List--an ordered collection, duplicates are allowed. Topic already discussed earlier.
Below are the 4 possible implementations of List.
List listA = new ArrayList();
List listB = new LinkedList();
List listC = new Vector();
List listD = new Stack();
http://tutorials.jenkov.com/java-collections/list.html
Un Ordered Structure
Set--An unordered collection with no duplicates.
Below are the 4 possible implementations of Set.
Set setA = new EnumSet();
Set setB = new HashSet();
Set setC = new LinkedHashSet();
Set setD = new TreeSet();
http://tutorials.jenkov.com/java-collections/set.html
http://www.vogella.com/tutorials/JavaDatastructures/article.html
Sorting
General Explanation for Various Sorting Algorithms:
Bubble Sort
http://www.youtube.com/watch?v=8Kp-8OGwphY
Selection Sort:
http://www.youtube.com/watch?v=f8hXR_Hvybo
Insertion Sort:
http://www.youtube.com/watch?v=DFG-XuyPYUQ
Merge Sort:
http://www.youtube.com/watch?v=EeQ8pwjQxTM
Student Assignment: Lab programs on various Sorting Algorithms (Thursday Lab HR)
Unit 2 question bNk 16 mark notes submission (Friday by EOD)
Source Code for Sorting Algorithms
Bubble Sort
http://www.algolist.net/Algorithms/Sorting/Bubble_sort
http://www.sorting-algorithms.com/bubble-sort
Selection Sort:
http://www.youtube.com/watch?v=f8hXR_Hvybo
http://www.algolist.net/Algorithms/Sorting/Selection_sort
http://www.sorting-algorithms.com/selection-sort
Merge Sort:
http://www.youtube.com/watch?v=EeQ8pwjQxTM
http://www.algolist.net/Algorithms/Merge/Sorted_arrays
http://www.sorting-algorithms.com/merge-sort
Insertion Sort:
http://www.youtube.com/watch?v=DFG-XuyPYUQ
http://www.algolist.net/Algorithms/Sorting/Insertion_sort
http://www.sorting-algorithms.com/insertion-sort
Trees
Binary Tree
Binary tree is a widely-used tree data structure. Feature of a binary tree, which distinguish it from
common tree, is that each node has at most two children. Each binary tree has following groups of
nodes:
● Root: the topmost node in a tree. It is a kind of "main node" in the tree, because all other nodes
can be reached from root. Also, root has no parent. It is the node, at which operations on tree
begin (commonly).
● Internal nodes: these nodes has a parent (root node is not an internal node) and at least one child.
● Leaf nodes: these nodes has a parent, but has no children.
Example of a binary tree
Operations
Basically, we can only define traversals for binary tree as possible operations: root-left-right
(preorder), left-right-root (postorder) and left-root-right (inorder) traversals. We will speak about them
in detail later.
Implementations
● Binary Search Tree (BST)
Binary Search Tree (BST)
General Idea of Trees:
http://www.youtube.com/watch?v=rSlFhunlpzI
Source Code for Binary Search Tree
http://www.youtube.com/watch?v=M6lYob8STMI
http://www.youtube.com/watch?v=UcOxGmj45AA
public class BinaryTree {
Node root;
public void addNode(int key, String name) {
// Create a new Node and initialize it
Node newNode = new Node(key, name);
// If there is no root this becomes root
if (root == null) {
root = newNode;
} else {
// Set root as the Node we will start
// with as we traverse the tree
Node focusNode = root;
// Future parent for our new Node
Node parent;
while (true) {
// root is the top parent so we start
// there
parent = focusNode;
// Check if the new node should go on
// the left side of the parent node
if (key < focusNode.key) {
// Switch focus to the left child
focusNode = focusNode.leftChild;
// If the left child has no children
if (focusNode == null) {
// then place the new node on the left of it
parent.leftChild = newNode;
return; // All Done
}
} else { // If we get here put the node on the right
focusNode = focusNode.rightChild;
// If the right child has no children
if (focusNode == null) {
// then place the new node on the right of it
parent.rightChild = newNode;
return; // All Done
}
}
}
}
}
// All nodes are visited in ascending order
// Recursion is used to go to one node and
// then go to its child nodes and so forth
public void inOrderTraverseTree(Node focusNode) {
if (focusNode != null) {
// Traverse the left node
inOrderTraverseTree(focusNode.leftChild);
// Visit the currently focused on node
System.out.println(focusNode);
// Traverse the right node
inOrderTraverseTree(focusNode.rightChild);
}
}
public void preorderTraverseTree(Node focusNode) {
if (focusNode != null) {
System.out.println(focusNode);
preorderTraverseTree(focusNode.leftChild);
preorderTraverseTree(focusNode.rightChild);
}
}
public void postOrderTraverseTree(Node focusNode) {
if (focusNode != null) {
postOrderTraverseTree(focusNode.leftChild);
postOrderTraverseTree(focusNode.rightChild);
System.out.println(focusNode);
}
}
public Node findNode(int key) {
// Start at the top of the tree
Node focusNode = root;
// While we haven't found the Node
// keep looking
while (focusNode.key != key) {
// If we should search to the left
if (key < focusNode.key) {
// Shift the focus Node to the left child
focusNode = focusNode.leftChild;
} else {
// Shift the focus Node to the right child
focusNode = focusNode.rightChild;
}
// The node wasn't found
if (focusNode == null)
return null;
}
return focusNode;
}
public static void main(String[] args) {
BinaryTree theTree = new BinaryTree();
theTree.addNode(50, "Boss");
theTree.addNode(25, "Vice President");
theTree.addNode(15, "Office Manager");
theTree.addNode(30, "Secretary");
theTree.addNode(75, "Sales Manager");
theTree.addNode(85, "Salesman 1");
// Different ways to traverse binary trees
// theTree.inOrderTraverseTree(theTree.root);
// theTree.preorderTraverseTree(theTree.root);
// theTree.postOrderTraverseTree(theTree.root);
// Find the node with key 75
System.out.println("nNode with the key 75");
System.out.println(theTree.findNode(75));
}
}
class Node {
int key;
String name;
Node leftChild;
Node rightChild;
Node(int key, String name) {
this.key = key;
this.name = name;
}
public String toString() {
return name + " has the key " + key;
/*
* return name + " has the key " + key + "nLeft Child: " + leftChild +
* "nRight Child: " + rightChild + "n";
*/
}
}

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Array properties
Array propertiesArray properties
Array properties
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
 
Java arrays
Java arraysJava arrays
Java arrays
 
9781439035665 ppt ch09
9781439035665 ppt ch099781439035665 ppt ch09
9781439035665 ppt ch09
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Collection and framework
Collection and frameworkCollection and framework
Collection and framework
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
 
Set data structure
Set data structure Set data structure
Set data structure
 
Array lecture
Array lectureArray lecture
Array lecture
 
Java arrays
Java arraysJava arrays
Java arrays
 
Python list
Python listPython list
Python list
 
Generics
GenericsGenerics
Generics
 
Practical cats
Practical catsPractical cats
Practical cats
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and Information
 
Array in Java
Array in JavaArray in Java
Array in Java
 
Arrays
ArraysArrays
Arrays
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 

Andere mochten auch

Linked list (java platform se 8 )
Linked list (java platform se 8 )Linked list (java platform se 8 )
Linked list (java platform se 8 )charan kumar
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-listpinakspatel
 
Data structures and algorithms made easy java
Data structures and algorithms made easy   javaData structures and algorithms made easy   java
Data structures and algorithms made easy javaCareerMonk Publications
 
Data Structures and Algorithms made Easy (Cover Page)
Data Structures and Algorithms made Easy (Cover Page)Data Structures and Algorithms made Easy (Cover Page)
Data Structures and Algorithms made Easy (Cover Page)CareerMonk Publications
 
Ime newsletter4
Ime newsletter4Ime newsletter4
Ime newsletter4royc1
 
Evolution 2016 - Programmatic a márkakampányokban - Ihász Ingrid
Evolution 2016 - Programmatic a márkakampányokban - Ihász IngridEvolution 2016 - Programmatic a márkakampányokban - Ihász Ingrid
Evolution 2016 - Programmatic a márkakampányokban - Ihász IngridMEC_Hungary
 
Harris Ait Presentation
Harris Ait PresentationHarris Ait Presentation
Harris Ait Presentationrogerharris
 
A YouTube szerepe a médiamixben workshop - Jobbágy Tamás előadása
A YouTube szerepe a médiamixben workshop -  Jobbágy Tamás előadásaA YouTube szerepe a médiamixben workshop -  Jobbágy Tamás előadása
A YouTube szerepe a médiamixben workshop - Jobbágy Tamás előadásaMEC_Hungary
 
IH 2015 - Változó idők, változó szerepek - Gulyás János
IH 2015 - Változó idők, változó szerepek - Gulyás JánosIH 2015 - Változó idők, változó szerepek - Gulyás János
IH 2015 - Változó idők, változó szerepek - Gulyás JánosMEC_Hungary
 
Social and digital media digital yearbook 2011 Adma
Social and digital media digital yearbook 2011 AdmaSocial and digital media digital yearbook 2011 Adma
Social and digital media digital yearbook 2011 AdmaJuan Sanchez Bonet
 
A nyero tartalom
A nyero tartalomA nyero tartalom
A nyero tartalomMEC_Hungary
 
Commendation of Service Excellence - Maybank Alan Lau
Commendation of Service Excellence - Maybank Alan LauCommendation of Service Excellence - Maybank Alan Lau
Commendation of Service Excellence - Maybank Alan LauNathaniel Han
 
Internationalization in java
Internationalization in javaInternationalization in java
Internationalization in javaArthik Daniel
 
Big picture 2015
Big picture 2015Big picture 2015
Big picture 2015MEC_Hungary
 

Andere mochten auch (20)

cblm-java-prog-ds
cblm-java-prog-dscblm-java-prog-ds
cblm-java-prog-ds
 
Linked list (java platform se 8 )
Linked list (java platform se 8 )Linked list (java platform se 8 )
Linked list (java platform se 8 )
 
Data structures
Data structuresData structures
Data structures
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
 
Final ds record
Final ds recordFinal ds record
Final ds record
 
Data structures and algorithms made easy java
Data structures and algorithms made easy   javaData structures and algorithms made easy   java
Data structures and algorithms made easy java
 
Data Structures and Algorithms made Easy (Cover Page)
Data Structures and Algorithms made Easy (Cover Page)Data Structures and Algorithms made Easy (Cover Page)
Data Structures and Algorithms made Easy (Cover Page)
 
Ime newsletter4
Ime newsletter4Ime newsletter4
Ime newsletter4
 
Evolution 2016 - Programmatic a márkakampányokban - Ihász Ingrid
Evolution 2016 - Programmatic a márkakampányokban - Ihász IngridEvolution 2016 - Programmatic a márkakampányokban - Ihász Ingrid
Evolution 2016 - Programmatic a márkakampányokban - Ihász Ingrid
 
Harris Ait Presentation
Harris Ait PresentationHarris Ait Presentation
Harris Ait Presentation
 
A YouTube szerepe a médiamixben workshop - Jobbágy Tamás előadása
A YouTube szerepe a médiamixben workshop -  Jobbágy Tamás előadásaA YouTube szerepe a médiamixben workshop -  Jobbágy Tamás előadása
A YouTube szerepe a médiamixben workshop - Jobbágy Tamás előadása
 
Manuel del Castillo Uribe
Manuel del Castillo UribeManuel del Castillo Uribe
Manuel del Castillo Uribe
 
IH 2015 - Változó idők, változó szerepek - Gulyás János
IH 2015 - Változó idők, változó szerepek - Gulyás JánosIH 2015 - Változó idők, változó szerepek - Gulyás János
IH 2015 - Változó idők, változó szerepek - Gulyás János
 
Social and digital media digital yearbook 2011 Adma
Social and digital media digital yearbook 2011 AdmaSocial and digital media digital yearbook 2011 Adma
Social and digital media digital yearbook 2011 Adma
 
A fantastic unit of english
A fantastic unit of englishA fantastic unit of english
A fantastic unit of english
 
A nyero tartalom
A nyero tartalomA nyero tartalom
A nyero tartalom
 
Commendation of Service Excellence - Maybank Alan Lau
Commendation of Service Excellence - Maybank Alan LauCommendation of Service Excellence - Maybank Alan Lau
Commendation of Service Excellence - Maybank Alan Lau
 
Internationalization in java
Internationalization in javaInternationalization in java
Internationalization in java
 
Big picture 2015
Big picture 2015Big picture 2015
Big picture 2015
 
Bibpm
BibpmBibpm
Bibpm
 

Ähnlich wie Aj unit2 notesjavadatastructures

16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks QueuesIntro C# Book
 
02 Arrays And Memory Mapping
02 Arrays And Memory Mapping02 Arrays And Memory Mapping
02 Arrays And Memory MappingQundeel
 
java I am trying to run my code but it is not letting me .pdf
java    I am trying to run my code but it is not letting me .pdfjava    I am trying to run my code but it is not letting me .pdf
java I am trying to run my code but it is not letting me .pdfadinathassociates
 
DATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCEDATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCEDev Chauhan
 
Abstract Algebra and Category Theory
Abstract Algebra and Category Theory Abstract Algebra and Category Theory
Abstract Algebra and Category Theory Naveenkumar Muguda
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaEdureka!
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#Shahzad
 
Array based based implementation of the List ADT It uses an array o.pdf
Array based based implementation of the List ADT It uses an array o.pdfArray based based implementation of the List ADT It uses an array o.pdf
Array based based implementation of the List ADT It uses an array o.pdfanithacells
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structuresmaznabili
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringRAJASEKHARV8
 
Engineering lecture ppt by venay magen
Engineering lecture ppt by venay magenEngineering lecture ppt by venay magen
Engineering lecture ppt by venay magenvenaymagen19
 
lec6.ppt
lec6.pptlec6.ppt
lec6.pptcawarir
 
DSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notesDSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notesswathirajstar
 

Ähnlich wie Aj unit2 notesjavadatastructures (20)

Chap09
Chap09Chap09
Chap09
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
 
02 Arrays And Memory Mapping
02 Arrays And Memory Mapping02 Arrays And Memory Mapping
02 Arrays And Memory Mapping
 
java I am trying to run my code but it is not letting me .pdf
java    I am trying to run my code but it is not letting me .pdfjava    I am trying to run my code but it is not letting me .pdf
java I am trying to run my code but it is not letting me .pdf
 
DATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCEDATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCE
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
 
Abstract Algebra and Category Theory
Abstract Algebra and Category Theory Abstract Algebra and Category Theory
Abstract Algebra and Category Theory
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
 
Oop lecture7
Oop lecture7Oop lecture7
Oop lecture7
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
 
Array based based implementation of the List ADT It uses an array o.pdf
Array based based implementation of the List ADT It uses an array o.pdfArray based based implementation of the List ADT It uses an array o.pdf
Array based based implementation of the List ADT It uses an array o.pdf
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structures
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and Engineering
 
Engineering lecture ppt by venay magen
Engineering lecture ppt by venay magenEngineering lecture ppt by venay magen
Engineering lecture ppt by venay magen
 
lec6.ppt
lec6.pptlec6.ppt
lec6.ppt
 
DSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notesDSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notes
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 
Collections
CollectionsCollections
Collections
 

Kürzlich hochgeladen

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 

Kürzlich hochgeladen (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 

Aj unit2 notesjavadatastructures

  • 1. UNIT II - JAVA DATA STRUCTURES Lists Linear Structures Arrays Stack Queue Linked List Ordered & Unordered Structures Order Structure Un Ordered Structure Sorting Trees Binary Tree Example of a binary tree Operations Implementations Binary Search Tree (BST) .
  • 2. Lists Collections API Revisit? List Abstract Data Type (ADT) • A list a collection of items in which the items have a position • We keep “to-do” lists, shop with a grocery list, and invite a list of friends to a party • Types of Lists – Ordered Lists - (implements Comparable Interface) • An ordered list is kept in order based on characteristics of the elements in the list, e.g. alphabetical order for names – Unordered Lists • They are stored in an order that is externally controlled by how and when the elements are added to the list – Indexed Lists Topics Discussed in URL: ● List Implementations ● Adding and Accessing Elements ● Removing Elements ● Generic Lists A List represents a data structure which allows to dynamically add, access and remove objects of the same type. Adding objects to the list is usually done via the add() method. The get(int i) method allows to retrieve the element at position i. Remove objects from the list is usually done via the remove(int i) method which removes the element at position i. Below is a sample program that explains the following: ● Custom List Implementation (using Arrays) which allows Adding, Accessing & Removing Elements ● Test Application that uses the above Customized List
  • 3. MyList.java package list; import java.util.Arrays; import java.util.Iterator; /** * Created by user on 2/15/14. */ public class MyList<E> { private int size = 0; private static final int DEFAULT_CAPACITY = 10; private Object elements[]; public MyList() { elements = new Object[DEFAULT_CAPACITY]; } public void add(E e) { if (size == elements.length) { ensureCapa(); } elements[size++] = e; } private void ensureCapa() { int newSize = elements.length * 2; elements = Arrays.copyOf(elements, newSize); } @SuppressWarnings("unchecked") public E get(int i) { if (i >= size || i < 0) { throw new IndexOutOfBoundsException("Index: " + i + ", Size " + i); } return (E) elements[i]; } public E remove(int i) { if (i >= size || i < 0) { throw new IndexOutOfBoundsException("Index: " + i + ", Size " + i); } size++; E oldValue = (E) elements[i]; int numMoved = size - i - 1; if (numMoved > 0) System.arraycopy(elements, i + 1, elements, i, numMoved); elements[--size] = null; return oldValue; } @Override public String toString() { String temp = new String(); temp = "["; for (int i = 0; i < elements.length; i++) { if (elements[i] != null) temp = temp + " "+ (E) elements[i] ; }
  • 4. temp = temp + "]"; return temp; } } The following show contains a small test for the data structure. I use in the first test the MyList implementation and in the second test the standard Java List implementation. MyMainListTest.java package list; import com.sun.org.apache.xpath.internal.SourceTree; import java.util.ArrayList; import java.util.List; /** * Created by user on 2/15/14. */ public class MyMainListTest { public static void main(String[] args) { MyMainListTest myMainListTest = new MyMainListTest(); System.out.println("Testing MyList"); try { myMainListTest.testMyList(); } catch (Exception e) { System.out.println("MyList " + e); } System.out.println("Testing StandardList"); try { myMainListTest.testStandardList(); } catch (Exception e) { System.out.println("StandardList " + e); } } public void testMyList() { MyList<Integer> list = new MyList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(3); list.add(4); list.add(2); list.add(3); list.add(3); list.add(4); list.add(2); list.add(3); list.add(3); list.add(4); System.out.println(list); //Remove element on 4th Index. list.remove(4); System.out.println(list); System.out.println(list.get(1));
  • 5. System.out.println(list.get(6)); System.out.println(list.get(20));//Throws IndexOutOfBoundsException System.out.println(list.get(-1));//Throws IndexOutOfBoundsException } public void testStandardList() { List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(3); list.add(4); list.add(2); list.add(3); list.add(3); list.add(4); list.add(2); list.add(3); list.add(3); list.add(4); System.out.println(list); //Remove element on 4th Index. list.remove(4); System.out.println(list); System.out.println(list.get(1)); System.out.println(list.get(6)); System.out.println(list.get(20));//Throws IndexOutOfBoundsException System.out.println(list.get(-1));//Throws IndexOutOfBoundsException } }
  • 6. Linear Structures Arrays Arrays are special data types that let us store specified number of variables from the same type using one variable name. An array is a sequence of data item of homogeneous value(same type). Why Arrays? Imagine the situation that you need to store 20 names of students as strings and 20 integers as marks, then you need to define 40 variables, and this is clearly very hard and not practical, in such case you need to use arrays. Arrays are indexed data types. As Figure shows, the size of an array is fixed, we will refer to array maximum size as array length , it is also clear that indices of an array are zero-based, that is, they start from 0 to length – 1;for example, the array shown in Figure has a length of 10 (stores up to 10 elements), and the last index is 9 Arrays are of two types: 1. One-dimensional arrays 2. Multidimensional arrays One-Dimensional Arrays ● Declaration ● Initialization (Construction) ● Accessing Elements (Read / Write) Multidimensional Arrays (Arrays of Arrays) ● Declaration ● Initialization (Construction) ● Accessing Elements (Read / Write)
  • 7. http://www.tutorialspoint.com/java/util/arraylist_get.htm Employee.java public class Employee implements Comparable { int EmpID; String Ename; double Sal; static int i; public Employee() { EmpID = i++; Ename = "dont know"; Sal = 0.0; } public Employee(String ename, double sal) { EmpID = i++; Ename = ename; Sal = sal; } public String toString() { return "EmpID " + EmpID + "n" + "Ename " + Ename + "n" + "Sal" + Sal; } public int compareTo(Object o1) { if (this.Sal == ((Employee) o1).Sal) return 0; else if ((this.Sal) > ((Employee) o1).Sal) return 1; else return -1; } } ComparableDemo.java import java.util.*; public class ComparableDemo{ public static void main(String[] args) { List ts1 = new ArrayList(); ts1.add(new Employee ("Tom",40000.00)); ts1.add(new Employee ("Harry",20000.00)); ts1.add(new Employee ("Maggie",50000.00)); ts1.add(new Employee ("Chris",70000.00)); Collections.sort(ts1);
  • 8. Iterator itr = ts1.iterator(); while(itr.hasNext()){ Object element = itr.next(); System.out.println(element + "n"); } } } Output: EmpID 1 Ename Harry Sal20000.0 EmpID 0 Ename Tom Sal40000.0 EmpID 2 Ename Maggie Sal50000.0 EmpID 3 Ename Chris Sal70000.0 http://math.hws.edu/javanotes/c7/index.html http://math.hws.edu/javanotes/c7/s3.html http://math.hws.edu/javanotes/c7/s5.html Stack Stack Implementation using Arrays http://www.vogella.com/tutorials/JavaDatastructures/article.html http://www.youtube.com/watch?v=sFVxsglODoo http://www.studytonight.com/data-structures/stack-data-structure http://tutorials.jenkov.com/java-collections/stack.html http://math.hws.edu/javanotes/c9/s3.html Queue Queue Implementation using Arrays http://www.youtube.com/watch?v=okr-XE8yTO8
  • 9. http://www.studytonight.com/data-structures/queue-data-structure http://tutorials.jenkov.com/java-collections/queue.html http://math.hws.edu/javanotes/c9/s3.html Linked List - Insert at Head - Insert at Last (Append) - Insert Middle Element - Insert After Element - Insert Before Element - Delete Head - Delete Last Element - Delete Middle Element http://www.cs.cmu.edu/~adamchik/15-121/lectures/Linked%20Lists/linked%20lists.html http://www.idevelopment.info/data/Programming/data_structures/java/LinkedList/LinkedList.shtml http://math.hws.edu/javanotes/c9/s2.html http://www.tutorialspoint.com/java/java_linkedlist_class.htm
  • 10. Ordered & Unordered Structures Order Structure List--an ordered collection, duplicates are allowed. Topic already discussed earlier. Below are the 4 possible implementations of List. List listA = new ArrayList(); List listB = new LinkedList(); List listC = new Vector(); List listD = new Stack(); http://tutorials.jenkov.com/java-collections/list.html Un Ordered Structure Set--An unordered collection with no duplicates. Below are the 4 possible implementations of Set. Set setA = new EnumSet(); Set setB = new HashSet(); Set setC = new LinkedHashSet(); Set setD = new TreeSet(); http://tutorials.jenkov.com/java-collections/set.html http://www.vogella.com/tutorials/JavaDatastructures/article.html
  • 11. Sorting General Explanation for Various Sorting Algorithms: Bubble Sort http://www.youtube.com/watch?v=8Kp-8OGwphY Selection Sort: http://www.youtube.com/watch?v=f8hXR_Hvybo Insertion Sort: http://www.youtube.com/watch?v=DFG-XuyPYUQ Merge Sort: http://www.youtube.com/watch?v=EeQ8pwjQxTM Student Assignment: Lab programs on various Sorting Algorithms (Thursday Lab HR) Unit 2 question bNk 16 mark notes submission (Friday by EOD) Source Code for Sorting Algorithms Bubble Sort http://www.algolist.net/Algorithms/Sorting/Bubble_sort http://www.sorting-algorithms.com/bubble-sort Selection Sort: http://www.youtube.com/watch?v=f8hXR_Hvybo http://www.algolist.net/Algorithms/Sorting/Selection_sort http://www.sorting-algorithms.com/selection-sort Merge Sort: http://www.youtube.com/watch?v=EeQ8pwjQxTM http://www.algolist.net/Algorithms/Merge/Sorted_arrays http://www.sorting-algorithms.com/merge-sort Insertion Sort: http://www.youtube.com/watch?v=DFG-XuyPYUQ http://www.algolist.net/Algorithms/Sorting/Insertion_sort http://www.sorting-algorithms.com/insertion-sort
  • 12. Trees Binary Tree Binary tree is a widely-used tree data structure. Feature of a binary tree, which distinguish it from common tree, is that each node has at most two children. Each binary tree has following groups of nodes: ● Root: the topmost node in a tree. It is a kind of "main node" in the tree, because all other nodes can be reached from root. Also, root has no parent. It is the node, at which operations on tree begin (commonly). ● Internal nodes: these nodes has a parent (root node is not an internal node) and at least one child. ● Leaf nodes: these nodes has a parent, but has no children. Example of a binary tree Operations Basically, we can only define traversals for binary tree as possible operations: root-left-right (preorder), left-right-root (postorder) and left-root-right (inorder) traversals. We will speak about them in detail later. Implementations ● Binary Search Tree (BST) Binary Search Tree (BST) General Idea of Trees: http://www.youtube.com/watch?v=rSlFhunlpzI Source Code for Binary Search Tree http://www.youtube.com/watch?v=M6lYob8STMI http://www.youtube.com/watch?v=UcOxGmj45AA public class BinaryTree { Node root; public void addNode(int key, String name) { // Create a new Node and initialize it Node newNode = new Node(key, name);
  • 13. // If there is no root this becomes root if (root == null) { root = newNode; } else { // Set root as the Node we will start // with as we traverse the tree Node focusNode = root; // Future parent for our new Node Node parent; while (true) { // root is the top parent so we start // there parent = focusNode; // Check if the new node should go on // the left side of the parent node if (key < focusNode.key) { // Switch focus to the left child focusNode = focusNode.leftChild; // If the left child has no children if (focusNode == null) { // then place the new node on the left of it parent.leftChild = newNode; return; // All Done } } else { // If we get here put the node on the right focusNode = focusNode.rightChild; // If the right child has no children if (focusNode == null) { // then place the new node on the right of it parent.rightChild = newNode; return; // All Done } }
  • 14. } } } // All nodes are visited in ascending order // Recursion is used to go to one node and // then go to its child nodes and so forth public void inOrderTraverseTree(Node focusNode) { if (focusNode != null) { // Traverse the left node inOrderTraverseTree(focusNode.leftChild); // Visit the currently focused on node System.out.println(focusNode); // Traverse the right node inOrderTraverseTree(focusNode.rightChild); } } public void preorderTraverseTree(Node focusNode) { if (focusNode != null) { System.out.println(focusNode); preorderTraverseTree(focusNode.leftChild); preorderTraverseTree(focusNode.rightChild); } } public void postOrderTraverseTree(Node focusNode) { if (focusNode != null) { postOrderTraverseTree(focusNode.leftChild); postOrderTraverseTree(focusNode.rightChild); System.out.println(focusNode); } } public Node findNode(int key) { // Start at the top of the tree Node focusNode = root; // While we haven't found the Node
  • 15. // keep looking while (focusNode.key != key) { // If we should search to the left if (key < focusNode.key) { // Shift the focus Node to the left child focusNode = focusNode.leftChild; } else { // Shift the focus Node to the right child focusNode = focusNode.rightChild; } // The node wasn't found if (focusNode == null) return null; } return focusNode; } public static void main(String[] args) { BinaryTree theTree = new BinaryTree(); theTree.addNode(50, "Boss"); theTree.addNode(25, "Vice President"); theTree.addNode(15, "Office Manager"); theTree.addNode(30, "Secretary"); theTree.addNode(75, "Sales Manager"); theTree.addNode(85, "Salesman 1"); // Different ways to traverse binary trees // theTree.inOrderTraverseTree(theTree.root); // theTree.preorderTraverseTree(theTree.root); // theTree.postOrderTraverseTree(theTree.root); // Find the node with key 75 System.out.println("nNode with the key 75"); System.out.println(theTree.findNode(75)); }
  • 16. } class Node { int key; String name; Node leftChild; Node rightChild; Node(int key, String name) { this.key = key; this.name = name; } public String toString() { return name + " has the key " + key; /* * return name + " has the key " + key + "nLeft Child: " + leftChild + * "nRight Child: " + rightChild + "n"; */ } }