I am creating a program that inserts a character (number/letter) into a binary tree. So far, I'm able to produce an output but it's not what I expected. These are the problems I'm encountering:
The
insertmethod is not able to print the correctheightof the tree. I am not sure where I should insert myheight ;statement to get the correct output.The
insertmethod is only able to add nodes to the right.
Expected Output:
ht=3 [K=3 L=[K=1 R=[K=2]] R=[K=5 L=[K=4]]]
My Output:
ht=4 [K=3 R=[K=1 R=[K=2 R=[K=5 R=[K=4]]]]
(all nodes are only added to the right 'R')
Here are my classes for reference:
Main Class
BST<Character> bst = new BST<>();
bst.insert('3');
bst.insert('1');
bst.insert('2');
bst.insert('5');
bst.insert('4');
System.out.println("ht=" bst.height " " bst.toString());
BST Class - where the insert method is declared
public class BST<T> extends BT<T> {
// insert() method
public void insert(char k)
{
if (root == null) {
root = new BTNode(k);
return;
}
BTNode<T> n = root;
BTNode<T> p = null; // parent
while (n != null) {
p = n;
if (k < n.value) {
n = n.left;
} else {
n = n.right;
}
}
if (k < p.value) {
p.left = new BTNode(k);
} else {
p.right = new BTNode(k);
height ; // adds 1 to height when a new level is made
}
}
}
BTNode Class
public class BTNode<T> {
T info;
int value, level;
BTNode<T> left, right;
public BTNode(T el) {
this(el, null, null);
}
public BTNode(T el, BTNode<T> l, BTNode<T> r) {
info = el;
left = l;
right = r;
}
}
BT Class - where the toString method is declared
public class BT<T> {
BTNode<T> root = null;
int height = 0;
public BT() {
BTNode<T> node = new BTNode("");
}
// other methods
// toString()
public String toString() {
return toString(root);
}
public String toString(BTNode<T> n) {
String s = "";
if (n == null) {
return "";
}
if (n != null) {
s = "[K=" n.info;
if (n.left != null) {
s = s " L=" toString(n.left) "]";
}
if (n.right != null) {
s = s " R=" toString(n.right) "]";
}
}
return s;
}
}
Hope you can help me out, thanks!
CodePudding user response:
You have quite a few issues in your code. I'll list a few immediate items but you really will need to learn to use an interactive debugger and unit testing to resolve the sorts of issues you are seeing.
You refer to the
valuefield inBTNodein your comparison but it is never set. You should really be referring toinfo(which is the actual data in the node).But given
infois a generic type you can't use standard comparison operators. Instead you'll need to define it as<T extends Comparable<T>>and then usen.info.compareTo(k) > 0.The key passed into insert should also be of type
TWhich means the other classes also need to ensure
TextendsComparable.Height is only incremented when nodes are added to the right which makes no sense.
You should get used to making your fields private and accessing them through getters. In your case a compareValue method would likely make sense.
