How to Save a Node - java

I've been coding a basic binary Tree in Java and have run into a problem. The goal of this program is to "learn" new questions in order to guess an animal similar to 20 questions. However, I have no idea how to "save" a node so it can be recalled by this same class the next time it runs. How to do this?
public class LearningTree {
Node root;
public void addNode(double key, String name){
Node newNode = new Node(key, name);
if (root == null){
root = newNode;
} else {
Node focusNode = root;
Node parent;
while(true){
parent = focusNode;`enter code here`
if(key < focusNode.key){
focusNode = focusNode.leftChild;
if(focusNode == null){
parent.leftChild = newNode;
return;
}
} else {
focusNode = focusNode.rightChild;
if(focusNode == null){
parent.rightChild = newNode;
return;
}
}
}
}
}
public void traverse(Node focusNode){
if(focusNode != null){
traverse(focusNode.leftChild);
traverse(focusNode.rightChild);
}
}
class Node{
double key;
String name;
Node leftChild;
Node rightChild;
Node(double key, String name){
this.key = key;
this.name = name;
}
}
public void keyChange(Node focusNode, double newkey){
focusNode.key = newkey;
}
public Node findNode(double key) {
Node focusNode = root;
while (focusNode.key != key) {
if (key < focusNode.key) {
focusNode = focusNode.leftChild;
} else {
focusNode = focusNode.rightChild;
}
if (focusNode == null)
return null;
}
return focusNode;
}
public static void main(String[] args){
LearningTree Tree = new LearningTree();
Scanner sc = new Scanner(System.in);
//Nodes
Tree.addNode(1500, "Does it have wings?");
Tree.addNode(750, "Is it a dog?");
System.out.println("Is it an animal?");
double n = 1000;
while(true){
String Answer = sc.nextLine();
String answer = Answer.toLowerCase();
double k = n;
if(answer.equals("y")){
n = 1.5* n;
}
if(answer.equals("n")){
n = .5*n;
}
if(Tree.findNode(n) != null){
System.out.println(Tree.findNode(n).name + " (y/n)");
}
if(Tree.findNode(n) == null){
System.out.println("What is it?");
String answer1 = sc.nextLine();
System.out.println("What would distinguish a " + answer1 + "from the previous guess?");
String answer2 = sc.nextLine();
System.out.println("What would the answer be to " + answer2 + "? (y/n)");
String answer3 = sc.nextLine();
double s;
if(Tree.findNode(k/1.5) == null){
Tree.findNode(k/.5);
} else {
Tree.findNode(k/1.5);
}
if(answer3.equals("y")){
Tree.keyChange(Tree.findNode(k), n );
s = 1.5;
Tree.addNode(n, Tree.findNode(n).name);
}
if(answer3.equals("n")){
Tree.keyChange(Tree.findNode(k), n);
s = .5;
Tree.addNode(n, Tree.findNode(n).name );
}
Tree.addNode(k, answer2);
}
}
}
}

Maybe you could use a local file and serialize the data. Java handles this pretty well.
NOTE: I haven't tested this code but it's a starting place.
private void saveNode(Node n){
FileOutputStream fout = new FileOutputStream("file.txt");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(n);
oos.close();
}
private Node readNode(){
FileInputStream fin = new FileInputStream("file.txt");
ObjectInputStream ois = new ObjectInputStream(fin);
Node n = (Node)ois.readObject();
ois.close();
return n;
}

You might want to serialize this object to a file so that it can get the data back when it runs next time through deserialize. Check ObjectOutputstream class's documentation. Having said that you need to have some logic to go with it,

Related

Create and Search BST from a txt file

I am currently in an intro data structures class and am really struggling with one of our problems about Binary Search Trees. This is the first time I have implemented this data structure and am doing my best to learn it.
Problem:
The program is supposed to create and search a BST of name and occurrence data, based upon the census data of babies born that year. We are given this data in a txt file.
I am having a lot of difficulty figuring out why it is not working. I am really just looking for someone to lead me in the right direction from here and give me some good feedback on what I already have because I feel really lost! My current work is below. I am implementing this in java. Thanks in advance!
public class Node {
String name;
int data;
Node leftChild;
Node rightChild;
public Node (String n, int d) {
name = n;
data = d;
}
public class BinarySearchTree` {
public static Node root;
public void addNode(String name, int data) {
Node newNode = new Node(name, data);
if (root == null) {
root = newNode;
} else {
Node focusNode = root;
Node parent;
while(true) {
parent = focusNode;
if (name.compareTo(focusNode.name) < 0) {
focusNode = focusNode.leftChild;
if (focusNode == null) {
parent.leftChild = newNode;
return;
} else {
focusNode = focusNode.rightChild;
if (focusNode == null) {
parent.rightChild = newNode;
return;
}
}
}
}
}
}
public Node searchName(String name) {
Node focusNode = root;
while (!focusNode.name.equals(name)) {
if (name.compareTo(focusNode.name) < 0) {
focusNode = focusNode.leftChild;
} else {
focusNode = focusNode.rightChild;
}
if (focusNode == null) {
return null;
}
}
return focusNode;
}
public static void main(String[] args) throws Exception {
BinarySearchTree tree = new BinarySearchTree();
FileReader file = new FileReader("/Users/mattspahr/Desktop/test.txt");
BufferedReader reader = new BufferedReader(file);
String str = null,
name = null,
num = null;
int data;
while(reader.readLine() != null) {
str = reader.readLine();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= '0' || c <= '9') {
name = str.substring(0, i);
}
num = str.replaceAll("[^0-9]" , "");
}
data = Integer.parseInt(num);
tree.addNode(name,data);
Node n = tree.searchName("Buffy ");
System.out.println(n);
}
}
}

How to store the number of times a recursion method calls itself by use of binary tree

I couldn't figure out how to store the number of times a recursive method calls itself. If any one could point me in the right direction I would greatly appreciate it! Below is my code in it i have a comment on where I think I am going wrong.
package module8_auriemma_assignment;
import java.util.*;
public class fibonacciTree{
Node root;
public void addNode(int key, int num) {
Node newNode = new Node(key, num);
if (root == null) {
root = newNode;
}
else {
Node focusNode = root;
Node parent;
while (true) {
parent = focusNode;
if (key < focusNode.key) {
focusNode = focusNode.leftChild;
if (focusNode == null) {
parent.leftChild = newNode;
return;
}
}
else
{
focusNode = focusNode.rightChild;
if (focusNode == null) {
// then place the new node on the right of it
parent.rightChild = newNode;
return; // All Done
}
}
}
}
}
public static void main(String[] args) {
fibonacciTree theTree = new fibonacciTree();
Scanner input = new Scanner (System.in);
System.out.println("Please enter an index");
System.out.println("I will compute your index's Fibonacci numbers.");
System.out.println("I will compute numbers that do not exceed a billion");
int number;
int key;
key = 0;
for(number = input.nextInt(); number < 1000000; number++){
System.out.println(fibonacci(number));
theTree.addNode(key, number);
/*
I am not sure if I should be adding a new node everytime the
loop happens in the main class OR if I should be having it store
a node inside of the fibonacci method itself
*/
number++;
key++;
}
}
public static long fibonacci(int i)
{
if (i == 0) return 0;
if (i <= 2) return 1;
long fibTerm = fibonacci(i - 1) + fibonacci(i - 2);
if(fibTerm > 1000000000){
System.out.println("Number too large");
System.exit(0);
}
else{
return fibTerm;
}
return fibTerm;
}
}
.
package module8_auriemma_assignment;
class Node {
int key;
int num;
Node leftChild;
Node rightChild;
Node(int key, int num) {
this.key = key;
this.num = num;
}
#Override
public String toString() {
return num + " has the key " + key;
}
}
fibonacci(int i) keeps calling itself until it is reduced to a series of 1+1+1+1+1+1+1+1+1+1+1+...
The solution is also the number of times the method is called. If you want to know how many times it was called, look at the return value.

What is the error in the following Queue implementation using linked list?

I wrote the following implementation of the queue using a linked list that does not maintain a reference to the tail node. When I try to print the queue, it outputs only the head i.e. only one node. What is the error? Thanks in advance!
package DataStructures;
import java.util.Scanner;
class Node {
int x;
Node nextNode;
public Node(int x) {
this.x = x;
nextNode = null;
}
}
class Queue {
Node head = null;
int n = 0;
public void enqueue(int x) {
if (n==0){
head = new Node(x);
n++;
return;
}
Node tempHead = head;
while (tempHead != null){
tempHead = tempHead.nextNode;
}
tempHead = new Node(x);
tempHead.nextNode = null;
n++;
}
public int dequeue() {
if (head == null) {
throw new Error("Queue under flow Error!");
} else {
int x = head.x;
head = head.nextNode;
return x;
}
}
public void printTheQueue() {
Node tempNode = head;
System.out.println("hi");
while (tempNode != null){
System.out.print(tempNode.x + " ");
tempNode = tempNode.nextNode;
}
}
}
public class QueueTest {
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
Queue queue = new Queue();
while (true){
int x = in.nextInt();
if (x == -1){
break;
} else{
queue.enqueue(x);
}
}
queue.printTheQueue();
}
}
You never assign a node to nextNode, so your list is either empty or consists of one node.
Here is a solution:
public void enqueue(int x) {
n++;
if (head == null) {
head = new Node(x);
else {
Node last = head;
while (last.nextNode != null)
last = last.nextNode;
last.nextNode = new Node(x);
}
}
Technically you don't need n but you could use it as cache for the size of the list. And you should decrease it in deque().
Make your enqueue to this:
public void enqueue(int x) {
if (n==0){
head = new Node(x);
head.nextNode=null;
n++;
return;
}
Node tempHead = head;
while (tempHead.nextNode!= null){
tempHead = tempHead.nextNode;
}
Node newNode = new Node(x);
tempHead.nextNode=newNode;
newNode.nextNode = null;
n++;
}

Java Binary Tree Validate

The point of this project is to get an array from the user and use it to create a tree using nodes. The next step is to call a method to check if it represents a Binary Tree. I've been working on this for hours and can't seem to find the correct method to check.
Here is my code so far. I have done everything but the isBinaryTree() method to check if it is a Binary Tree.
import java.util.Scanner;
public class TestBinaryTree
{
Node root;
public void addNode(int key)
{
Node newNode = new Node(key);
if(root == null)
{
root = newNode;
}
else
{
Node focusNode = root;
Node parent;
while(true)
{
parent = focusNode;
if(key < focusNode.key)
{
focusNode = focusNode.leftChild;
if(focusNode == null)
{
parent.leftChild = newNode;
return;
}
}
else
{
focusNode = focusNode.rightChild;
if(focusNode == null)
{
parent.rightChild = newNode;
return;
}
}
}
}
}
/*public static boolean isBinaryTree(int rt, int lft, int rght)
{
}*/
public static void main(String[] args)
{
int Nroot, Nleft, Nright;
Scanner input = new Scanner(System.in);
TestBinaryTree theTree = new TestBinaryTree();
System.out.println("How many numbers are in the array: ");
int num = input.nextInt();
int arr[]=new int[num];
System.out.println("Enter the numbers: ");
for(int i=0;i<num;i++)
{
arr[i] = input.nextInt();
theTree.addNode(arr[i]);
}
}
}
class Node
{
int key;
Node leftChild;
Node rightChild;
Node(int key)
{
this.key = key;
}
public String toString()
{
return "Node: " + key;
}
}

How to sort a Linked list

I created a linked list using nodes that prints out a list(string) of names. I'm trying to write a sort method that prints out the names in alphabetical order. If this was integers it would be easy but I have no idea how to go about doing this. Any help or tips are appreciated.
-I cannot use the builtin collections.sort(). I need to make my own method.
SortMethod: (this is what I used when I was printing a list of numbers out but now its strings so I know I can't use the > operator. I just don't know how to replace it.
public void Sort( BigNode front)
{
BigNode first,second,temp;
first= front;
while(first!=null) {
second = first.next;
while(second!=null) {
if(first.dataitems < second.dataitems)
{
temp = new BigNode();
temp.dataitems =first.dataitems;
first.dataitems = second.dataitems;
second.dataitems = temp.dataitems;
}
second=second.next;
}
Heres the rest of program(I dont think its needed but just in case)
import java.util.*;
public class BigNode {
public String dataitems;
public BigNode next;
BigNode front ;
BigNode current;
String a = "1", b = "2", c = "3", d = "4";
String[] listlength;
public void initList(){
front = null;
}
public BigNode makeNode(String number){
BigNode newNode;
newNode = new BigNode();
newNode.dataitems = number;
newNode.next = null;
return newNode;
}
public boolean isListEmpty(BigNode front){
boolean balance;
if (front == null){
balance = true;
}
else {
balance = false;
}
return balance;
}
public BigNode findTail(BigNode front) {
BigNode current;
current = front;
while(current.next != null){
//System.out.print(current.dataitems);
current = current.next;
} //System.out.println(current.dataitems);
return current;
}
public void addNode(BigNode front ,String name){
BigNode tail;
if(isListEmpty(front)){
this.front = makeNode(name);
}
else {
tail = findTail(front);
tail.next = makeNode(name);
}
}
public void addAfter(BigNode n, String dataItem2) { // n might need to be front
BigNode temp, newNode;
temp = n.next;
newNode = makeNode(dataItem2);
n.next = newNode;
newNode.next = temp;
}
public void findNode(BigNode front, String value) {
boolean found , searching;
BigNode curr;
curr = front;
found = false;
searching = true;
while ((!found) && (searching)) {
if (curr == null) {
searching = false;
}
else if (curr.dataitems == value) { // Not sure if dataitems should be there (.data in notes)
found = true;
}
else {
curr = curr.next;
}
}
System.out.println(curr.dataitems);
}
public void deleteNode(BigNode front, String value) {
BigNode curr, previous = null; boolean found;
if (!isListEmpty(front)){
curr = front;
found = false;
while ((curr.next != null) && (!found)) {
if(curr.dataitems.equals(value)) {
found = true;
}
else {
previous = curr;
curr = curr.next;
}
}
if (!found) {
if(curr.dataitems.equals(value)) {
found = true;
}
}
if (found) {
if (curr.dataitems.equals(front.dataitems)){ // front.dataitems may be wrong .dataitems
front = curr.next;
} else {
previous.next = curr.next;
}
} else {
System.out.println("Node not found!");
//curr.next = null; // Not sure If this is needed
}
}
showList(front);
}
public void printNodes(String[] len){
listlength = len;
int j;
for (j = 0; j < len.length; j++){
addNode(front, len[j]);
} showList(front);
}
public void showList(BigNode front){
current = front;
while ( current.next != null){
System.out.print(current.dataitems + ", ");
current = current.next;
}
System.out.println(current.dataitems);
MenuOptions();
}
public void MenuOptions() {
Scanner in = new Scanner(System.in);
System.out.println("Choose an Option Below:");
System.out.println(a + "(Display Length of List)" + ", " + b + "(Delete a person)" + ", " + c + ("(Exit)"));
String pick = in.nextLine();
if (pick.equals(b)) {
System.out.println("Who would you like to delete?");
String delete = in.nextLine();
deleteNode(front, delete);
}
if (pick.equals(a)) {
System.out.println("Length of List = " + listlength.length);
MenuOptions();
}
if (pick.equals(c)) {
}
}
public static void main(String[] args) {
String[] names = {"Billy Joe", "Sally Mae", "Joe Blow", "Tasha Blue", "Malcom Floyd"}; // Trying to print theses names..Possibly in alphabetical order
BigNode x = new BigNode();
x.printNodes(names);
}
}
first.dataitems.compareTo(second.dataitems)<0
or if you have a comparator
comp.compare(first.dataitems, second.dataitems)<0

Categories