I have a bit of a conundrum. I need to print all the values in my BST that are NOT keys. So since the tree is not ordered according to these values, I can't do as I normally have with BSTs in the past. I simply need to look at EVERY node on the tree, compare the non-key value with the value I have entered, and determine whether to print it.
I.E. Student directory where I need to print all GPAs above a 2.0. Since the tree is ordered by Student IDs and not GPA, how do I go through every node and compare GPA and print all nodes that are above 2.0?
If you need to look at my code, the whole thing is here, and it's enormous.
public class StudentBST
{
private static Node root;
static class Node
{
public int studentID;
public String lastName;
public String firstName;
public String major;
public double gpa;
public Node left, right;
public int minValue()
{
if(left == null)
{
return studentID;
}
else
{
return left.minValue();
}
}
public boolean remove(int i, Node node)
{
if(i < this.studentID)
{
if(left != null)
{
return left.remove(i, this);
}
else
{
return false;
}
}
else if(i > this.studentID)
{
if(right != null)
{
return right.remove(i, this);
}
else
{
return false;
}
}
else
{
if(left != null && right != null)
{
this.studentID = right.minValue();
right.remove(this.studentID, this);
}
else if(node.left == this)
{
node.left = (left != null) ? left : right;
}
else if(node.right == this)
{
node.right = (left != null) ? left : right;
}
return true;
}
}
public Node(int i, String l, String f, String m, double g)
{
studentID = i;
lastName = l;
firstName = f;
major = m;
gpa = g;
left = null;
right = null;
}
}
public StudentBST()
{
root = null;
}
private static void insert(int i, String l, String f, String m, double g)
{
root = insert(root, i, l, f, m , g);
}
private static Node insert(Node node, int i, String l, String f, String m, double g)
{
if(node == null)
{
node = new Node(i, l, f, m, g);
}
else
{
if(i <= node.studentID)
{
node.left = insert(node.left, i, l, f, m, g);
}
else
{
node.right = insert(node.right, i, l, f, m, g);
}
}
return(node);
}
public static void printBST()
{
printBST(root);
System.out.println();
}
private static void printBST(Node node)
{
if(node == null)
{
return;
}
printBST(node.left);
System.out.println(node.studentID + ", " + node.lastName + ", " + node.firstName
+ ", " + node.major + ", " + node.gpa);
printBST(node.right);
}
public static boolean remove(int i)
{
if(root == null)
{
return false;
}
else
{
if(root.studentID == i)
{
Node auxRoot = new Node(0, "", "", "", 0);
auxRoot.left = root;
boolean result = root.remove(i, auxRoot);
root = auxRoot.left;
return result;
}
else
{
return root.remove(i, null);
}
}
}
public static void main(String[] args)
{
StudentBST.insert(8, "Costanza", "George", "Napping", 1.60);
StudentBST.insert(10, "Kramer", "Cosmo", "Chemistry", 3.04);
StudentBST.insert(5, "Seinfeld", "Jerry", "Theater", 2.05);
StudentBST.printBST();
Scanner input = new Scanner(System.in);
int option = 9;
while(option != 0)
{
System.out.println("1 - Add new student 2 - Delete student 3 - Print All" +
" 0 - Exit");
option = input.nextInt();
if(option == 1)
{
System.out.println("Enter student ID");
int i = input.nextInt();
input.nextLine();
System.out.println("Enter Last Name");
String l = input.nextLine();
System.out.println("Enter First Name");
String f = input.nextLine();
System.out.println("Enter major");
String m = input.nextLine();
System.out.println("Enter GPA");
Double g = input.nextDouble();
System.out.println("Inserted student record");
StudentBST.insert(i, l, f, m, g);
}
if(option == 2)
{
System.out.println("Enter Student ID to delete");
int i = input.nextInt();
boolean b = StudentBST.remove(i);
if(b)
{
System.out.println("Deletion completed");
}
else
{
System.out.println("Deletion encountered error");
}
}
if(option == 3)
{
StudentBST.printBST();
}
}
}
I think you have the right idea: just walk across the whole tree and print out GPAs higher than a certain threshold. A rough implementation looks like:
public void printGPAs(Node node, double gpa_cutoff) {
if (node == null) {
return;
}
if (node.gpa >= gpa_cutoff) {
System.out.println(node.gpa);
}
printGPAs(node.left);
printGPAs(node.right);
}
If you wanted to print them out in a particular order, the easiest way would be to drop them in to a list as you go along, inserting in the correct place to maintain your desired order.
Related
I am currently learning binary search tree. For a school assignment, I want to implement an self-balancing binary search tree (I choose AVL tree); however, the Node class cannot be modified. I cannot use the common implementation of the AVL tree (I can't store height inside the node).
This is the source code that I implemented (using HashMap).
public class Tree {
static class Student {
String id;
String name;
public Student(String id, String name) {
this.id = id;
this.name = name;
}
public String toString() {return id + ", " + name;}
}
private class Node {
Student e;
public Node lc, rc; // left child; right child
#SuppressWarnings("unused")
public Node(Student data) {
this.e = data;
}
public String toString() {
return e.toString();
}
}
Node root;
public HashMap<Node, Integer> map = new HashMap<>();
public void insert(Student s) {
root = insert(root, s);
}
public Node insert(Node curNode, Student s){
if (curNode == null){
Node newNode = new Node(s);
map.put(newNode, 1);
return newNode;
}
else if (s.name.compareTo(curNode.e.name) < 0)
curNode.lc = insert(curNode.lc, s);
else if (s.name.compareTo(curNode.e.name) > 0)
curNode.rc = insert(curNode.rc, s);
else return curNode;
int l, r;
map.put(curNode, max(nheight(curNode.rc),
nheight(curNode.lc)) + 1);
int balance = getBalance(curNode);
if (balance > 1 && s.name.compareTo(curNode.e.name) < 0)
return rightRotate(curNode);
if (balance < -1 && s.name.compareTo(curNode.e.name) > 0)
return leftRotate(curNode);
if(balance > 1 && s.name.compareTo(curNode.e.name) > 0){
curNode.lc = leftRotate(curNode.lc);
return rightRotate(curNode);
}
if(balance < -1 && s.name.compareTo(curNode.e.name) < 0){
curNode.rc = rightRotate(curNode.rc);
return leftRotate(curNode);
}
return curNode;
}
public int max(int a, int b){
return a > b ? a : b;
}
public int nheight(Node curRoot){
if (curRoot == null) return 0;
return map.get(curRoot);
}
public int getBalance(Node curNode){
if (curNode == null) return 0;
return nheight(curNode.lc) - nheight(curNode.rc);
}
public Node rightRotate(Node y){
Node x = y.lc;
Node T2 = x.rc;
x.rc = y;
y.lc = T2;
map.put(y, max(nheight(y.lc), nheight(y.rc)) + 1);
map.put(x, max(nheight(x.lc), nheight(x.rc)) + 1);
return x;
}
public Node leftRotate(Node x){
Node y = x.rc;
Node T2 = y.lc;
y.lc = x;
x.rc = T2;
map.put(x, max(nheight(x.lc), nheight(x.rc)) + 1);
map.put(y, max(nheight(y.lc), nheight(y.rc)) + 1);
return y;
}
}
I tried using a HashMap<Node, Integer> to store the height of each node, and using recursive method to calculate the height and balance factor every time. For small number of nodes, the above two methods would work; however, for large node size (>=1000000) those methods will not work. Is there any other data structures I can use the keep track of the height of each node?
This is the code I used to test. I randomly created 1000000 students with names and ids and insert them into the AVL tree.
public class Main {
public static void main(String[] args) {
Tree tree = new Tree();
String[] surnames = {"Chan", "Leung", "Li", "Lai", "Cheung", "Yeung", "Tang", "Chow", "Fung", "Tsang", "Kwok", "Chu", "Liu", "Wong", "Mak"};
SecureRandom random = new SecureRandom();
String[] names = new String[1000000];
for (int j = 0; j < names.length; j++) {
StringBuilder a = new StringBuilder();
for(int i = 0; i < 5; i ++) {
a.append((char)('a' + random.nextInt(25)));
}
names[j] = surnames[random.nextInt(surnames.length)] + " " + a.toString();
}
int id = 22222222;
for (String name : names) {
id += random.nextInt(100);
tree.insert(new Tree.Student(String.valueOf(id), name));
}
}
}
The code works fine when the size of the String is 1000 (String[1000]). It gets error when the size of String gets larger. For example, when it gets to 1000000. The error code is below.
Exception in thread "main" java.lang.NullPointerException: Cannot read field "lc" because "y" is null
Problem found. A careless mistake. I was focusing too much on the size of the input. The actual problem is with the insertion and rotations.
The amended code.
public Node insert(Node curNode, Student s){
if (curNode == null){
Node newNode = new Node(s);
map.put(newNode, 1);
return newNode;
}
else if (s.name.compareTo(curNode.e.name) < 0)
curNode.lc = insert(curNode.lc, s);
else if (s.name.compareTo(curNode.e.name) > 0)
curNode.rc = insert(curNode.rc, s);
else return curNode;
int l, r;
map.put(curNode, max(nheight(curNode.rc), nheight(curNode.lc)) + 1);
int balance = getBalance(curNode);
if (balance > 1 && s.name.compareTo(curNode.lc.e.name) < 0)
return rightRotate(curNode);
if (balance < -1 && s.name.compareTo(curNode.rc.e.name) > 0)
return leftRotate(curNode);
if(balance > 1 && s.name.compareTo(curNode.lc.e.name) > 0){
curNode.lc = leftRotate(curNode.lc);
return rightRotate(curNode);
}
if(balance < -1 && s.name.compareTo(curNode.rc.e.name) < 0){
curNode.rc = rightRotate(curNode.rc);
return leftRotate(curNode);
}
return curNode;
}
I'm new to Java and programming in general. The code works, mostly. It can do everything except for when I input the following:
Sequence: d, e, f, a, b, c, g, h, i, j.
Search for: b or c
I can't seem to find any issue with the code but have narrowed it down to the insertNode module/class, it seems like when users key in a, b, c after d, e, f, only node a register on the left side.
import java.util.Arrays;
import java.util.Scanner;
import java.lang.reflect.Method;
public class BinarySearchTreeTestStackOverflow {
class Node {
String stringData;
Node leftChild;
Node rightChild;
Node(String stringData) {
this.stringData = stringData;
leftChild = rightChild = null;
}
}
//root node for the binary tree
Node root;
//Constructor method
public BinarySearchTreeTestStackOverflow() {
root = null;
}
//Insert method for new values in the tree
public void insert(String key) {
root = insertNode(root, key);
}
//Insert recursive call for inserting from the root, in the right place
public Node insertNode(Node node, String key) {
if (node == null) {
node = new Node(key);
return node;
}
if (key.compareTo(node.stringData) < 0) {
node.leftChild = insertNode(node.leftChild, key);
} else if (key.compareTo(root.stringData) > 0) {
node.rightChild = insertNode(node.rightChild, key);
}
return node;
}
//Find method asking for the node to find
public Node find(String key) { //takes user input and turns it into a node
Node node = findNode(root, key);
System.out.println("print key to find: " + key);
return node;
}
//Find recursive method using the root node.
public Node findNode(Node node, String key) {
if (key.compareTo(node.stringData) == 0) {
return node;
}
//check up on findNodeMethod
if (key.compareTo(node.stringData) <= 0) {
if (node.leftChild == null) {
return null;
} else {
return findNode(node.leftChild, key);
}
} else if (key.compareTo(node.stringData) > 0) {
if (node.rightChild == null) {
return null;
} else {
System.out.println("went right"); //toDelete
return findNode(node.rightChild, key);
}
}
return null;
}
public static void main(String[] args) {
BinarySearchTreeTestStackOverflow binaryTree = new BinarySearchTreeTestStackOverflow();
Scanner scanner = new Scanner(System.in);
for (int i = 1; i <= 10; i++) {
System.out.print("Enter string " + i + " for the tree: ");
binaryTree.insert(scanner.nextLine());
}
System.out.print("Enter the value to be searched: ");
String key = scanner.nextLine(); //correct, verified using - System.out.println("key to be searched: "+ key);
Node node = binaryTree.find(key);
if (node == null) {
System.out.println("The string does not exist");
} else {
System.out.println("Node " + node.stringData + " was found");
}
}
}
The issue is inside insertNode(). Instead of comparing with root:
else if (key.compareTo(root.stringData) > 0) {
node.rightChild = insertNode(node.rightChild, key);
}
you should compare with node:
else if (key.compareTo(node.stringData) > 0) {
node.rightChild = insertNode(node.rightChild, key);
}
I have an assignment for my Data Structures class. In the assignment, we have to implement polynomial addition using linked lists. I think I have it down but eclipse is giving me a null pointer exception. My problem is with the add method, though I included the whole class for context. Multiply I will tackle after.. Please help.
class PolynomialLinkedList{
private static class PNode{
private int coe;
private int exp;
private PNode next;
public PNode(int c, int e){
this(c, e, null);
}
public PNode(int c, int e, PNode n){
coe = c;
exp = e;
next = n;
}
public void setCoe(int c){ coe = c;}
public void setExp(int e){ exp = e;}
public void setNext(PNode n){ next = n;}
public int getCoe(){ return coe;}
public int getExp(){ return exp;}
public PNode getNext(){ return next;}
}
private PNode first;
private PNode last;
public PolynomialLinkedList(){
first = last = null;
}
public PolynomialLinkedList(int c, int e){
PNode tempn = new PNode(c, e);
first = last = tempn;
}
public void print(){
if (first == null){
System.out.println();
return;
}
PNode temp = first;
String ans = "";
while (temp != null){
if (temp.getCoe() > 0) {
if (temp != first) ans = ans + " + ";
ans = ans + temp.getCoe();
}
else if (temp.getCoe() < 0) ans = ans + " - " + temp.getCoe() * -1;
if (temp.getExp() != 0){
ans = ans + "X^" + temp.getExp();
}
temp = temp.getNext();
}
System.out.println(ans);
}
public PolynomialLinkedList add(PolynomialLinkedList s){
PolynomialLinkedList sum = new PolynomialLinkedList();
PNode temp1 = this.first;
PNode temp2 = s.first;
PNode tempAns = new PNode(0,0);
if(temp1.exp != temp2.exp) {
while(temp1.exp > temp2.exp) {
tempAns.setCoe(temp1.coe);
tempAns.setExp(temp1.exp);
temp1 = temp1.getNext();
tempAns = sum.first.getNext();
}
while(temp1.exp < temp2.exp) {
tempAns.setCoe(temp2.coe);
tempAns.setExp(temp2.exp);
temp2 = temp2.getNext();
tempAns = sum.first.getNext();
}
}
else if(temp1.exp == temp2.exp) {
while(temp1.exp == temp2.exp) {
tempAns.setCoe((temp1.coe + temp2.coe));
tempAns.setExp(temp1.exp);
temp1 = temp1.getNext();
temp2 = temp2.getNext();
tempAns = sum.first.getNext();
}
}
return sum;
}
public PolynomialLinkedList multiply(PolynomialLinkedList s){
PolynomialLinkedList product = new PolynomialLinkedList();
//implement this method
return product;
}
}
The error I believe starts on line 102: int treeDepth(Node Node) because when I run the code with a regular while loop with a count, it runs and displays a tree. But as soon as I change the while condition to while (treeDepth(this.root) <= 5) it runs but displays nothing, and I get no errors. Trying to make it so the tree that is created doesn't have a depth larger than 5.
import java.io.*;
import java.util.*;
class Node {
int value;
Node left;
Node right;
Node(int value) {
this.value = value;
right = null;
left = null;
}
}
public class treeStructureBinary{
Node root;
public static void main(String[] args) {
treeStructureBinary bn =new treeStructureBinary();
bn.appMain(args);
}
void appMain(String[] args) {
createBinaryTree();
}
private Node addRecursive(Node current, int value) {
if (current == null) {
return new Node(value);
}
if (value < current.value) {
current.left = addRecursive(current.left, value);
} else if (value > current.value) {
current.right = addRecursive(current.right, value);
} else {
return current;
}
return current;
}
public void add(int value) {
this.root = addRecursive(this.root, value);
}
public treeStructureBinary createBinaryTree() {
treeStructureBinary bt = new treeStructureBinary();
int [] array = new int[89];
int counter = 0;
boolean check = true;
while (treeDepth(this.root) <= 5)
{
Random rand = new Random();
int n = rand.nextInt(89) + 10;
for(int z = 0; z <= counter; z++)
{
if ( n == array[z])
{
check = false;
break;
}
}
if (check == true)
{
bt.add(n);
array[counter] = n;
counter++;
}
check = true;
}
bt.traverseLevelOrder();
return bt;
}
public void traverseLevelOrder() {
if (this.root == null) {
return;
}
Queue<Node> nodes = new LinkedList<>();
nodes.add(this.root);
while (!nodes.isEmpty()) {
Node node = nodes.remove();
System.out.print(" " + node.value);
if (node.left != null) {
nodes.add(node.left);
}
if (node.right != null) {
nodes.add(node.right);
}
}
}
int treeDepth(Node Node){
if (Node == null) {
return 0;
}else {
int lDepth = treeDepth(Node.left);
int rDepth = treeDepth(Node.right);
if (lDepth > rDepth) {
System.out.println("lDepth" + "\n");
return (lDepth + 1);
}else {
System.out.println("rDepth" + "\n");
return (rDepth + 1);
}
}
}
}
I think your addRecursive never actually adds the node to the tree--or always adds it? Anyway it looks funky. I'd focus on that for a bit.
This code in particular:
if (value < current.value) {
current.left = addRecursive(current.left, value);
} else if (value > current.value) {
current.right = addRecursive(current.right, value);
} else {
return current;
}
always forces an assign (even if it's not a leaf) and the final else will only execute when value == current.value which is probably not what you want.
I don't really want to go much further because it looks homeworky and you'll gain more figuring it out yourself.
It might work anyway (You just may be re-assigning every node at every level) but I'm not sure without running it.
Anyway, if this is a homework assignment I'd really like to commend you on your style, it's one of the best I've seen posted here for a homework-like question.
Main problem here is that you are working on two different trees.
First you create one tree in main function:
public static void main(String[] args) {
treeStructureBinary bn =new treeStructureBinary();
bn.appMain(args);
}
Then you create another one in createBinaryTree method:
public SthApplication createBinaryTree() {
treeStructureBinary bt = new treeStructureBinary();
See, you used new keyword twice, so there will be two objects.
Later in your app you refer to this.root (which is the one from main), but some methods use local variable bt.
In example, treeDepth(this.root) operates on different tree then the bt.add(n), so it goes into infinite loop.
If you solve that problem, you will know how to finish the rest.
Thanks guys I figured it out!
import java.io.*;
import java.util.*;
class Node {
int value;
int balancefactor;
int nodex;
Node left;
Node right;
Node(int value, int balancefactor, int nodex) {
this.value = value;
this.balancefactor = balancefactor;
this.nodex = nodex;
this.right = null;
this.left = null;
}
}
public class treeStructureBinary{
Node root;
public static void main(String[] args) {
treeStructureBinary bn =new treeStructureBinary();
bn.appMain(args);
}
void appMain(String[] args) {
int count = args.length;
if (count >1) {
count = 1;
}
String [] cmdln = {""};
for (int i=0;i<count;i++) {
cmdln[i]=args[i];
}
if (cmdln[0].equals("BT")){
createBinaryTree();
} else if (cmdln[0].equals("AVL")) {
} else {
System.out.println("Please enter BT or AVL to choose the type of
tree.");
}
}
private Node addRecursive(Node current, int value, int balancefactor, int
nodex) {
if (current == null) {
return new Node(value, balancefactor, nodex);
} if (value < current.value) {
balancefactor++;
nodex=(nodex*2);
current.left = addRecursive(current.left, value, balancefactor,
nodex);
} else if (value > current.value) {
balancefactor++;
nodex=(nodex*2)+1;
current.right = addRecursive(current.right, value, balancefactor,
nodex);
} else {
return current;
}
return current;
}
public void add(int value) {
int balancefactor=1;
int nodex=0;
this.root = addRecursive(this.root, value, balancefactor, nodex);
}
public treeStructureBinary createBinaryTree() {
treeStructureBinary bt = new treeStructureBinary();
int [] array = new int[89];
int counter = 0;
boolean check = true;
int temp = 0;
while (temp < 5) {
Random rand = new Random();
int n = rand.nextInt(89) + 10;
for(int z = 0; z <= counter; z++) {
if ( n == array[z]) {
check = false;
break;
}
}
if (check == true) {
bt.add(n);
array[counter] = n;
counter++;
}
check = true;
temp = bt.treeDepth();
}
bt.traverseLevelOrder();
Scanner reader =new Scanner(System.in);
System.out.println("\n\nEnter a number to delete or 0 to exit");
int input = reader.nextInt();
Boolean isMatch = true;
while (input!=0) {
for(int p = 0; p < counter; p++)
{
//System.out.println(array[p]);
if (input != array[p])
{
isMatch = false;
}
else
{
isMatch = true;
array[p] = 0;
break;
}
}
if (isMatch == false )
{
System.out.println("Error, number not found.");
}
bt.nodeDelete(input);
bt.traverseLevelOrder();
System.out.println("\n\nEnter a number to delete or 0 to exit");
input = reader.nextInt();
}
return bt;
}
public void traverseLevelOrder() {
int count = 0;
int outer = 31;
int inner = 30;
int lastnode= 0;
int check = 0;
if (this.root == null) {
return;
}
Queue<Node> nodes = new LinkedList<>();
nodes.add(this.root);
while (!nodes.isEmpty()) {
Node node = nodes.remove();
if (count < node.balancefactor) {
System.out.print("\n");
for (int i=0; i<outer; i++) {
System.out.print(" ");
}
inner=outer;
outer=outer/2;
count++;
lastnode=0;
check=0;
}
check=((node.nodex-lastnode));
for (int i=0; i<(inner*check*2);i++) {
System.out.print(" ");
}
if (check >1) {
for (int j=0;j<check;j++) {
System.out.print(" ");
}
}
lastnode=node.nodex;
System.out.print(node.value);
if (node.left != null) {
nodes.add(node.left);
}
if (node.right != null) {
if (node.right==null &&lastnode == 0) {
if (count==5) {
break;
}
System.out.print(" ");
}
nodes.add(node.right);
}
}
}
int treeDepth(){
int temp = treeDepthRecursive(this.root);
return temp;
}
int treeDepthRecursive(Node current) {
if (current == null) {
return 0;
} else {
int lDepth = treeDepthRecursive(current.left);
int rDepth = treeDepthRecursive(current.right);
if (lDepth > rDepth) {
return (lDepth + 1);
} else {
return (rDepth + 1);
}
}
}
public void nodeDelete(int value) {
nodeDeleteRecursive(root, value);
}
public Node nodeDeleteRecursive(Node current, int value) {
if (current == null) {
return null;
}
if (value == current.value) {
if (current.left ==null && current.right==null) {
return null;
}
if (current.right==null) {
return current.left;
}
if (current.left==null) {
return current.right;
}
int sValue = findSmall(current.right);
current.value = sValue;
current.right = nodeDeleteRecursive(current.right, sValue);
return current;
}
if (value < current.value) {
current.left = nodeDeleteRecursive(current.left, value);
return current;
}
current.right =nodeDeleteRecursive(current.right, value);
return current;
}
public int findSmall(Node root) {
return root.left == null?(root.value):(findSmall(root.left));
}
}
I have a txtfile with a list of unsorted numbers. I took the list of numbers and made an array. So now i'm trying to make a tree with those numbers and sort them out based off of what on the left and right. Right now its printing, but not sorted. I'm pretty sure the tree isn't being made right but I'm not sure how to fix it. I also want to keep track of any duplicates. In other words I don't want to print out any duplicates but instead just keep track of how many there are. Any help or advice is appreciated. Thanks in advance.
-- I pass the array of numbers in method: dealArray(), which then converts it to a int. From there those #'s are passed in findDuplicate() which I'm not sure I should be doing or not.
BigTree Class:
public class bigTree {
int data; int frequency;
bigTree Left, Right;
public bigTree makeTree(int x) {
bigTree p;
p = new bigTree();
p.data = x;
p.Left = null;
p.Right = null;
return p;
}
public void setLeft(bigTree t, int x) {
if (t.Left != null) {
System.out.println("Error");
}
else {
bigTree q;
q = t.Left;
q = makeTree(x);
}
}
public void setRight(bigTree t, int x) {
if (t.Right != null) {
System.out.println("Error");
} else {
bigTree q;
q = t.Right;
q = makeTree(x);
}
}
public void findDuplicate(int number) {
bigTree tree, p, q;
frequency = 0;
tree = makeTree(number);
//while (//there are still #'s in the list) { //1st while()
p = tree;
q = tree;
while (number != p.data && q != null) { //2nd while()
p = q;
if (number < p.data ) {
q = q.Left;
} else {
q = q.Right;
}
} //end of 2nd while()
if (number == p.data) {
Sort(p);
//System.out.println( p.data );
frequency++;
}
else {
if (number < p.data) {
setLeft(p,number);
}
else {
setRight(p, number);
}
}
//} // End of 1st while()
}
public void Sort(bigTree t) {
if (t.Left != null) {
Sort(t.Left);
}
System.out.println(t.data);
if (t.Right != null) {
Sort(t.Right);
}
//Possible print
}
public void dealArray(String[] x) {
int convert;
for (int i = 0; i < x.length; i++){
convert = Integer.parseInt(x[i]);
findDuplicate(convert);
// System.out.println(x[i]);
}
}
Rather than trying to find duplicates ahead of time, find them while building your Tree.
Your tree should probably consist of a Node like the following:
public class Node {
public int number;
public int count;
public Node left;
public Node right;
}
Build up your Binary Search Tree (There are a million tutorials on this). While adding a new element, if you find that element already exists, increment your count for that node.
Then printing is a matter of pre-order traversal (Again, there are a million tutorials on this)
Use the implementation below for hints on how to do it. Sorry I currently cannot format the code and remove the unnecessary methods.
import java.util.*;
public class TreeNode implements Iterator , Iterable{
public Object value;
public TreeNode prev;
public TreeNode left;
public TreeNode right;
private TreeNode w;
public TreeNode(){
}
public TreeNode(Object value){
this.value= value;
}
public Object[] toArray(){
Object[] a= new Object[this.size()];
int i= 0;
for(Object o : this){
a[i]= o;
i++;
}
return a;
}
public TreeNode delete(Object o){
TreeNode z= this.findNode(o);
if(z==null){
return this;
}
if(z.left != null && z.right != null){
TreeNode z1= z.right.minNode();
z.value= z1.value;
z= z1;
}
if(z.left == null && z.right == null){
TreeNode y= z.prev;
if(y==null){
return null;
}
if(y.right == z){
y.right= null;
}else{
y.left= null;
}
return this;
}
if(z.left == null || z.right == null){
TreeNode y;
if(z.left != null){
y= z.left;
}else{
y= z.right;
}
if(z.prev == null){
y.prev= null;
return y;
}else{
y.prev= z.prev;
if(z.prev.left == z){
z.prev.left= y;
}else{
z.prev.right= y;
}
}
}
return this;
}
public boolean hasNext(){
return w != null;
}
public Object next(){
Object d= w.value;
w= w.nextNode();
return d;
}
public void remove(){
}
public Iterator iterator(){
w= this.minNode();
return this;
}
public Object min(){
if(this.left == null){
return this.value;
}
return this.left.min();
}
public TreeNode minNode(){
if(this.left == null){
return this;
}
return this.left.minNode();
}
public Object max(){
if(this.right == null){
return this.value;
}
return this.right.max();
}
public void print(){
System.out.println(this.value);
if(left != null){
this.left.print();
}
if(right != null){
this.right.print();
}
}
public void printSort(){
if(left != null){
this.left.printSort();
}
System.out.println(this.value);
if(right != null){
this.right.printSort();
}
}
public static String intervals(int n, int p){
String s= " ";
return s.substring(0, n*p);
}
public void printTree(int p){
printTree0(1, p);
}
public void printTree0(int d, int p){
if(this.right != null){
this.right.printTree0(d+1, p);
}
System.out.println(intervals(d, p) + this.value);
if(this.left != null){
this.left.printTree0(d+1, p);
}
}
public boolean add(Object o){
if(this.value.equals(o)){
return false;
}
if( ((Comparable)this.value).compareTo(o) > 0 ){ //left
if(left != null){
left.add(o);
}else{
left= new TreeNode(o);
left.prev= this;
}
}else{ // right
if(right != null){
right.add(o);
}else{
right= new TreeNode(o);
right.prev= this;
}
}
return true;
}
public void addBalanced(Object o){
int l= rang(this.left);
int r= rang(this.right);
boolean ldir= true;
if(l == r){
int ls= size(this.left);
int rs= size(this.right);
if(ls > rs){
ldir= false;
}
}else{
ldir= l <= r;
}
if(ldir){
if(this.left==null){
this.left= new TreeNode(o);
}else{
this.left.addBalanced(o);
}
}else{
if(this.right==null){
this.right= new TreeNode(o);
}else{
this.right.addBalanced(o);
}
}
}
public TreeNode nextNode(){
if(this.right != null){
return this.right.minNode();
}
TreeNode t1= this;
TreeNode t2= this.prev;
while(t2!=null && t2.right==t1){
t1= t2;
t2= t2.prev;
}
return t2;
}
public TreeNode findNode(Object o){
if(this.value.equals(o)){
return this;
}
if( ((Comparable)this.value).compareTo(o) > 0 ){ //left
if(left != null){
return left.findNode(o);
}
}else{ // right
if(right != null){
return right.findNode(o);
}
}
return null;
}
public int size(){
int n= 1;
if(this.left != null){
n= n + this.left.size();
}
if(this.right != null){
n= n + this.right.size();
}
return n;
}
public static int size(TreeNode t){
if(t==null){
return 0;
}
return 1 + TreeNode.size(t.left) + TreeNode.size(t.right);
}
public int rang(){
int l= 0;
int r= 0;
if(left!=null){
l= left.rang();
}
if(right!=null){
r= right.rang();
}
return 1 +( (l > r) ? l : r ) ;
}
public static int rang(TreeNode t){
if(t==null){
return 0;
}
int l= rang(t.left);
int r= rang(t.right);
return 1 +( (l > r) ? l : r ) ;
}
public String toString(){
return "( " + value + " " + left + " " + right + " )";
}
/*
public String toString(){
String s= "( " + this.value + " ";
if(this.left == null && this.right == null){
return s + ")";
}
if(this.left==null){
s= s + "( )";
}else{
s= s + this.left;
}
if(this.right==null){
s= s + "( )";
}else{
s= s + this.right;
}
return s + ")";
}
*/
}