EDIT: proper solution:
void add(Student s)
{
if(root == null)
root = new TreeNode(s);
else
insert(root,s);
}
void insert(TreeNode tn, Student s)
{
if(tn.sVal.compareTo(s) > 0)
{
if(tn.left != null)
insert(tn.left, s);
else
{
tn.left = new TreeNode(s);
tn.left.parent = tn;
}
}
else if(tn.sVal.compareTo(s) < 0)
{
if(tn.right != null)
insert(tn.right, s);
else
{
tn.right = new TreeNode(s);
tn.right.parent = tn;
}
}
balance(tn);
}
I’m trying to inserting to a binary tree using the following:
void add(Student s)
{
insert(root,s);
}
private void insert(TreeNode t, Student s)
{
if(t == null)
t = new TreeNode(s);
else if(t.sVal.compareTo(s) > 0)
insert(t.right, s);
else if(t.sVal.compareTo(s) < 0)
insert(t.left,s);
}
However, the tree remains empty, and I can’t figure out why. I hate to be so vague, but I can’t find an error in the logic. What am I missing?
Here’s a big hint: Make this change first, then debug from there:
And a still bigger hint: When you create the new node, you must also have a reference to its parent so you can add it to the parent.