Hi I'm currently trying to build a Java BST with some online references, but I have a problem during my insertion as I realize it does not create a tree after I tried to do inOrder traversal, after some attempts I found issue when passing the root into my insertion method.
My Node class:
public class TreeNode
{
String m_key;
Object m_value;
TreeNode m_left;
TreeNode m_right;
//constructor
public TreeNode(String inKey, Object inVal)
{
if(inKey==null)
{
throw new IllegalArgumentException("Key cannot be null.");
}
m_key = inKey;
m_value = inVal;
m_left = null;
m_right = null;
}
}
My insert method:
public void insert(String key, Object data)
{
m_root = insertRec(m_root, key, data);
}
private TreeNode insertRec(TreeNode x, String key, Object val)
{
if(x == null)
{
x = new TreeNode(key,val);
}
int cmp = key.compareTo(x.m_key);
if(cmp<0)
{
x.m_left = insertRec(x.m_left, key, val);
}
else if(cmp>0)
{
x.m_right = insertRec(x.m_right, key, val);
}
else
{
x.m_value = val;
}
return x;
}
print root:
public void printRoot()
{
System.out.println("the root is: " + m_root.m_key);
}
My main class:
public static void main(String[] args)
{
binaryTree bt = new binaryTree();
bt.insert("a", "data a");
bt.insert("b", "data b");
bt.insert("c", "data c");
bt.printRoot();
}
I got "a" as root result from printing root, and I tried to print root.m_left it shows null. Is there something I could've missed?
The recursive part after the first if-statement
will always be executed. Also, given it's a BST, if comp <= 0
recur left
:
if(x == null) {
x = new TreeNode(key,val);
} else {
int cmp = key.compareTo(x.m_key);
if(cmp <= 0) {
x.m_left = insertRec(x.m_left, key, val);
} else {
x.m_right = insertRec(x.m_right, key, val);
}
}
return x;