- The document discusses various Java data structures including lists, arrays, stacks, queues, linked lists, binary trees, and binary search trees.
- It provides code examples for implementing a custom list using arrays, as well as examples for common list operations like adding, accessing, and removing elements.
- Additional code examples demonstrate binary tree traversal methods like inorder, preorder, and postorder traversals, as well as methods for inserting nodes and searching for nodes in a binary search tree.
An Introduction to Programming in Java: ArraysMartin Chapman
An Introduction to Programming in Java: Arrays. Last delivered in 2012. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Array Basics
Copying Arrays
Passing Arrays to Methods
Returning an Array from a Method
(Optional) Variable-Length Argument Lists
The Arrays Class
Two-Dimensional Arrays
(Optional) Multidimensional Arrays
An Introduction to Programming in Java: ArraysMartin Chapman
An Introduction to Programming in Java: Arrays. Last delivered in 2012. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Array Basics
Copying Arrays
Passing Arrays to Methods
Returning an Array from a Method
(Optional) Variable-Length Argument Lists
The Arrays Class
Two-Dimensional Arrays
(Optional) Multidimensional Arrays
Arrays In Python | Python Array Operations | EdurekaEdureka!
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on 'Arrays in Python' will help you establish a strong hold on all the fundamentals in the Python programming language. Below are the topics covered in this PPT:
What is an array?
Is python list same as an array?
How to create arrays in python?
Accessing array elements
Basic array operations
- Finding the length of an array
- Adding Elements
- Removing elements
- Array concatenation
- Slicing
- Looping
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Other than some generic containers like list, Python in its definition can also handle containers with specified data types. Array can be handled in python by module named “array“. They can be useful when we have to manipulate only a specific data type values.
• List is a collection, which is ordered and changeable. Allows duplicate members.
• Tuple is a collection, which is ordered and unchangeable. Allows duplicate members.
• Set is a collection, which is unordered and unindexed. No duplicate members.
• Dictionary is a collection, which is unordered, changeable and indexed. No duplicate members.
Java collection classes and their usage.how to use java collections in a program and different types of collections. difference between the map list set, volatile keyword.
Arrays In Python | Python Array Operations | EdurekaEdureka!
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on 'Arrays in Python' will help you establish a strong hold on all the fundamentals in the Python programming language. Below are the topics covered in this PPT:
What is an array?
Is python list same as an array?
How to create arrays in python?
Accessing array elements
Basic array operations
- Finding the length of an array
- Adding Elements
- Removing elements
- Array concatenation
- Slicing
- Looping
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Other than some generic containers like list, Python in its definition can also handle containers with specified data types. Array can be handled in python by module named “array“. They can be useful when we have to manipulate only a specific data type values.
• List is a collection, which is ordered and changeable. Allows duplicate members.
• Tuple is a collection, which is ordered and unchangeable. Allows duplicate members.
• Set is a collection, which is unordered and unindexed. No duplicate members.
• Dictionary is a collection, which is unordered, changeable and indexed. No duplicate members.
Java collection classes and their usage.how to use java collections in a program and different types of collections. difference between the map list set, volatile keyword.
Success key book for:
* Campus Preparation
* Degree/Masters Course Preparation
* Instructor’s
* GATE Preparation
* Big job hunters: Microsoft, Google, Amazon, Yahoo, Flip Kart, Adobe, IBM Labs, Citrix, Mentor Graphics, NetApp, Oracle, Webaroo, De-Shaw, Success Factors, Face book, McAfee and many more
* Reference Manual for working people
The Asia Digital Marketing Association (ADMA), in cooperation with leading digital marketing companies and researchers, has published the fifth annual Asia Pacific Digital Marketing Yearbook. This edition has expanded market-by-market sections with the inclusion of social media, as well as more information than ever before on online demographics, user behaviour, online advertising, mobile, and e-commerce. The Yearbook is compiled for use by marketers, advertisers, their agencies, and anyone looking to maximise the digital potential of their business in the region.
The Yearbook is available now in an 98-page printed edition for members, and as a free download at www.asiadigitalmarketingyearbook.com.
In this chapter we are going to get familiar with some of the basic presentations of data in programming: lists and linear data structures. Very often in order to solve a given problem we need to work with a sequence of elements. For example, to read completely this book we have to read sequentially each page, i.e. to traverse sequentially each of the elements of the set of the pages in the book. Depending on the task, we have to apply different operations on this set of data. In this chapter we will introduce the concept of abstract data types (ADT) and will explain how a certain ADT can have multiple different implementations. After that we shall explore how and when to use lists and their implementations (linked list, doubly-linked list and array-list). We are going to see how for a given task one structure may be more convenient than another. We are going to consider the structures "stack" and "queue", as well as their applications. We are going to get familiar with some implementations of these structures.
java I am trying to run my code but it is not letting me .pdfadinathassociates
java
I am trying to run my code but it is not letting me i dont know what i should do or fix. Thank you so
much for your help. This is the problem and my code will be on the bottom.
Problem #1 and Only
Dynamic Array of Integers Class
Create a class named DynamicArray that will have convenient functionality similar to JavaScripts
Array object and Javas ArrayList class. The class allows to store array of integers that can grow
and shrink as needed, search for values, remove elements, etc.
You are not allowed to use ArrayList object as well as any methods from java.util.Arrays
class.
Please see the list of required features and methods below.
private int array[] You MUST store the data internally in a regular partially-filled array of integers.
Please DO NOT USE ArrayList. The size of the allocated array is its capacity and will be
discussed below.
private int size. This variable stores the number of occupied elements in the array. Set to 0 in the
constructor.
Constructor with parameter. The parameter defines the capacity (length) of initial array. Allocates
array of given capacity (length), sets size field to 0. In case the parameter given to constructor is 0
or negative, IllegalArgumentException is being thrown.
No-argument constructor. Allocates array of length 3, assigns it to the array field, sets size field to
0.
Copy constructor. The constructor takes an object of type DynamicArray as a parameter and
copies it into the object it creates. The constructor throws IllegalArgumentException if the object
that was passed to copy from is null.
int getSize() returns the number of occupied elements in the array.
int getCapacity() returns the actual size (length) of the partially-filled array
int [] getArray() accessor returns the entire partially-filled array. Make sure you DO NOT return the
private array field, make a copy of it.
int [] toArray() accessor returns an occupied part of the partially-filled array. Make sure you DO
NOT return the private array field. Instead, allocate memory for the new array, copy the occupied
portion of the field into that new object, and return the new array.
public void push(int num) adds a new element to the end of the array and increments the size
field. If the array is full, you need to increase the capacity of the array:
Create a new array with the size equal to double the capacity of the original one.
Copy all the elements from the array field to the new array.
Add the new element to the end of the new array.
Use new array as an array field.
Make sure your method works well when new elements are added to an empty DynamicArray.
public int pop() throws RuntimeException removes the last element of the array and returns it.
Decrements the size field. If the array is empty a RuntimeException with the message Array is
empty must be thrown. At this point check the capacity of the array. If the capacity is 4 times larger
than the number of occupied elements (size), it is time to shrink the array:
Create a new array wi.
Data processing is an integral part of most modern software development. Understanding of Abstract Algebra and Category theory will be beneficial for addressing data processing concerns.
( ** Java Certification Training: https://www.edureka.co/java-j2ee-soa-training ** )
This Edureka tutorial on “Java ArrayList” (Java blog series: https://goo.gl/osrGrS) will give you a brief insight about ArrayList in Java and its various constructors and methods along with an example. Through this tutorial, you will learn the following topics:
Collections Framework
Hierarchy of ArrayList
What is ArrayList
Internal Working of ArrayList
Constructors of ArrayList
Constructors Example
ArrayList Methods
Methods Example and Demo
Advantages of ArrayList over Arrays
Check out our Java Tutorial blog series: https://goo.gl/osrGrS
Check out our complete Youtube playlist here: https://goo.gl/CRbgFann
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Array based based implementation of the List ADT It uses an array o.pdfanithacells
Array based based implementation of the List ADT: It uses an array of specific maximum length,
and storage is allocated to before run time.
public class ListArrayBased implements ListInterface
{
private static final int MAX_LIST = 50;
private Object items[];
s private int numItems;
public ListArrayBased()
{
items = new Object[MAX_LIST];
numItems = 0;
}
public boolean isEmpty()
{
return (numItems = = 0);
}
{return numItems;
}
{
if (index >= 1 && index <= numItems)
{return items[translate(index)];
}
else {throws new ListIndexOutOfBoundsException(“index OutOfRange on get”);
}
}
It is list of linear sequence of arbitary number of items together with the following procedures
like
createlist(): It is used to create an empty list
Add(index,,item)
remove(index)
isempty
get(index)
size
Solution
Array based based implementation of the List ADT: It uses an array of specific maximum length,
and storage is allocated to before run time.
public class ListArrayBased implements ListInterface
{
private static final int MAX_LIST = 50;
private Object items[];
s private int numItems;
public ListArrayBased()
{
items = new Object[MAX_LIST];
numItems = 0;
}
public boolean isEmpty()
{
return (numItems = = 0);
}
{return numItems;
}
{
if (index >= 1 && index <= numItems)
{return items[translate(index)];
}
else {throws new ListIndexOutOfBoundsException(“index OutOfRange on get”);
}
}
It is list of linear sequence of arbitary number of items together with the following procedures
like
createlist(): It is used to create an empty list
Add(index,,item)
remove(index)
isempty
get(index)
size.
Engineering lecture ppt by venay magenvenaymagen19
Venay Magen likes the shading red, particularly on Tuesdays. He cherishes to drink bourbon (on all days). He figured out how to drink whisky from his youth companion Zippo, when they went to class together at Mount Temple Comprehensive School. He is best known as the lead vocalist for the band MN3.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Accelerate your Kubernetes clusters with Varnish Caching
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
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";
*/
}
}