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 + ")";
}
*/
}
Related
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));
}
}
Sorry in advance for all the code provided, because I am unsure where the problem may be, I am adding the whole thing.
I am having trouble getting my program to output anything (just blank space). A great deal of this code comes straight from our book and what isn't is also from previous (yet similar) programs that I have gotten to work. I have been mainly focusing on the levelOrder and insert methods, though I'm thinking it may be the latter.
import java.util.Scanner;
import java.lang.*;
public class AVLTree {
private static class AvlNode {
int key;
AvlNode left;
AvlNode right;
int height; //height difference between right and left subtrees at node
AvlNode(int x) {
key = x;
left = right = null;
height = 0;
}
AvlNode( int x, AvlNode l, AvlNode r) {
key = x;
left = l;
right = r;
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean keepRunning = true;
while (keepRunning) {
System.out.print(">> Enter choice [1-7] from menu below: \n");
System.out.println("\t 1) Insert node");
System.out.println("\t 2) Remove node");
System.out.println("\t 3) Print level order");
System.out.println("\t 4) Exit program ");
int choice = input.nextInt();
int value;
switch (choice)
{
case 1:
System.out.print("Enter element to insert: ");
value = input.nextInt();
insert(value, root);
break;
case 2:
System.out.print("Enter element to remove: ");
value = input.nextInt();
remove(value);
break;
case 3:
levelOrder();
System.out.println("");
break;
case 4:
keepRunning = false;
break;
default:
System.out.println("Invalid Choice!");
keepRunning = false;
}
}
}
private static AvlNode root;
public AvlNode getroot() {
return root;
}
private static int height(AvlNode t) {
if(t == null) {
return 1;
}
else
return t.height;
}
private static final int ALLOWED_IMBALANCE = 1;
private static AvlNode balance(AvlNode t) {
if (t == null) {
return t;
}
if (height(t.left) - height(t.right) > ALLOWED_IMBALANCE) {
if (height(t.left.left) >= height(t.left.right)) {
t = singleRotateLL(t);
} else {
t = doubleRotateLR(t);
}
} else {
if (height(t.right) - height(t.left) > ALLOWED_IMBALANCE) {
if (height(t.right.right) >= height(t.right.left)) {
t = singleRotateRL(t);
} else {
t = doubleRotateRL(t);
}
}
}
t.height = Math.max(height(t.left), height(t.right)) + 1;
return t;
}
//public methods for insert, remove, findMin, findMax, find....
//The find function will not require modification because they do not change the structure of the tree
private static AvlNode singleRotateLL(AvlNode k2) {
AvlNode k1 = k2.left; //next make "poiner" adjustments for the LL rotate operation
k2.left = k1.right;
k1.right = k2;
k2.height = Math.max(height(k2.left), height(k2.right)) + 1;
k1.height = Math.max(height(k1.left), height(k1.right)) + 1;
return k1;
}
private static AvlNode doubleRotateLR(AvlNode k3) {
AvlNode k1 = k3.left; //next make "poiner" adjustments for the LL rotate operation
AvlNode k2 = k1.right;
k1.right = k2.left;
k3.left = k2.right;
k2.left = k1;
k2.right = k3;
k1.height = Math.max(height(k1.left), height(k1.right)) + 1;
k2.height = Math.max(height(k2.left), height(k2.right)) + 1;
k3.height = Math.max(height(k3.left), height(k3.right)) + 1;
return k2;
}
private static AvlNode singleRotateRL(AvlNode k2) {
AvlNode k1 = k2.right; //next make "poiner" adjustments for the LL rotate operation
k2.right = k1.left;
k1.left = k2;
k2.height = Math.max(height(k2.right), height(k2.left)) + 1;
k1.height = Math.max(height(k1.right), height(k1.left)) + 1;
return k1;
}
private static AvlNode doubleRotateRL(AvlNode k3) {
AvlNode k1 = k3.right; //next make "poiner" adjustments for the LL rotate operation
AvlNode k2 = k1.left;
k1.left = k2.right;
k3.right = k2.left;
k2.right = k1;
k2.left = k3;
k1.height = Math.max(height(k1.right), height(k1.left)) + 1;
k2.height = Math.max(height(k2.right), height(k2.left)) + 1;
k3.height = Math.max(height(k3.right), height(k3.left)) + 1;
return k2;
}
private static AvlNode insert(int x, AvlNode t) {
if(t == null)
return new AvlNode(x, null, null);
int compareResult = Integer.compare(x, t.key);
if(compareResult < 0) {
t.left = insert(x, t.left);
}
else if(compareResult > 0) {
t.right = insert(x, t.right);
}
else; // duplicate, do nothing
return balance(t);
}
public int findMin() {
return findMin(root).key;
}
private static AvlNode findMin(AvlNode t) {
if (t == null) {
return null;
}
if (t.left == null) {
return t;
}
return findMin(t.left);
}
public static void remove(int x) {
remove(x, root);
}
private static AvlNode remove(int x, AvlNode t) {
if (t == null) {
return t;
}
int compareResult = Integer.compare(x, t.key);
if (compareResult < 0) {
t.left = remove(x, t.left);
}
else if (compareResult > 0) {
t.right = remove(x, t.right);
}
else if ((t.left != null) && (t.right != null)) {
t.key = findMin(t.right).key;
t.right = remove(t.key, t.right);
}
else {
t = (t.left != null) ? t.left : t.right;
}
return balance(t);
}
private static void levelOrder() { //prints the level order traversal of the tree
int h = height(root);
for(int i = 1; i <= h; i++) {
printLevel(root, i);
}
}
private static void printLevel(AvlNode t, int level) {
if(t == null) {
return;
}
if(level == 1) {
System.out.print(t.key + " ");
}
else if(level > 1) {
printLevel(t.left, level - 1);
printLevel(t.right, level - 1);
}
}
}
You had to do two changes, one is to initialize root and the first time, and the second one is to change the height accordingly.
Just change the following class & function :
private static AvlNode insert(int x, AvlNode t) {
if (t == null && root==null)
return (root = new AvlNode(x, null, null));
else if (t==null) {
return new AvlNode(x, null, null);
}
t.height++;
int compareResult = Integer.compare(x, t.key);
if (compareResult < 0) {
t.left = insert(x, t.left);
} else if (compareResult > 0) {
t.right = insert(x, t.right);
} else {
t.height--;
}
return balance(t);
}
private static class AvlNode {
int key;
AvlNode left;
AvlNode right;
int height=0;
AvlNode(int x, AvlNode l, AvlNode r) {
key = x;
left = l;
right = r;
this.height++;
}
}
I am trying to write a method that returns the depth of a target int in a binary search tree. Right now it works for some smaller trees, but not always. Does anyone see where I may be going wrong?
static int count=1;
public static int findDepth(TreeNode<Integer> root, int target)
// pre: 0 or more elements in the tree, integer to search for
// post: return depth of target if found, -1 otherwise
{
count++;
if (root!=null)
{
if (root.getValue()<target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
else
{findDepth(root.getLeft(), target);
count--;
findDepth(root.getRight(), target);
}
}
else if (root.getValue()>target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
else
{findDepth(root.getLeft(), target);
count--;
findDepth(root.getRight(), target);
}
}
else if (root.getValue()==target)
return 1;
else
return -1;
}
return count;
}
There's a few things wrong.
It will never get into this case:
if (root.getValue()<target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
Also it will never get into this case:
else if (root.getValue()>target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
The biggest issue is that you're keeping a global static count, and recursively going through both left and right paths.
First of all, for a BST, there is no need to go both left and right.
Second, it's better to pass the count through a parameter rather than keeping a global.
Rather than fix your code, I'll post this working example for you to use as a reference:
public class Main
{
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.add(20);
tree.add(10);
tree.add(30);
tree.add(15);
tree.add(25);
tree.add(5);
tree.add(35);
tree.add(1);
tree.add(6);
tree.add(14);
tree.add(16);
tree.add(24);
tree.add(26);
tree.add(34);
tree.add(36);
int level = tree.getLevel(6);
System.out.println(level);
}
}
public class TreeNode
{
int data;
TreeNode left;
TreeNode right;
public TreeNode(int d){
data = d;
left = null;
right = null;
}
}
public class BinaryTree
{
TreeNode root;
public BinaryTree(){
root = null;
}
public int getLevel(int val) {
if (root == null) return 0;
return getLevelHelper(root, val, 0);
}
public int getLevelHelper(TreeNode node, int val, int level){
int retVal = -1;
if (node.data == val){
return level;
}
if (val < node.data && node.left != null){
retVal = getLevelHelper(node.left, val, level + 1);
}
else if (val > node.data && node.right != null){
retVal = getLevelHelper(node.right, val, level + 1);
}
return retVal;
}
public boolean add(int newData){
if (root == null){
root = new TreeNode(newData);
return true;
}
else{
TreeNode curr = root;
while (true){
if (curr.data == newData){
return false;
}
else if (curr.data > newData){
if (curr.left == null){
curr.left = new TreeNode(newData);
return true;
}
else{
curr = curr.left;
}
}
else{
if (curr.right == null){
curr.right = new TreeNode(newData);
return true;
}
else{
curr = curr.right;
}
}
}
}
}
}
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.