I\'m having problems trying to make the insert part work in my code. I\'m allowe
ID: 3828543 • Letter: I
Question
I'm having problems trying to make the insert part work in my code. I'm allowed to have //private Node mRoot; in my BST constructor. The Node is a private class in BST.
public class BST {
private Node mRoot;
public BST()
{
Node mRoot = new Node ("");
}
public void insert(String key)
{
Node newNode = new Node(key);
if(key.compareTo(mData) < 0)
{
if(mLeft == null)
{
mLeft == null);
newNode.mParent = this;
return;
}
else
{
mLeft.insert(key);
}
}
else
{
if(mRight == null)
{
mRight == null);
newNode.mParent = this;
return;
}
else
{
mRight.insert(key);
}
}
}
private class Node
{
public Node(String data)
{
mData = data;
mParent = null;
mLeft = mRight = null;
}
private String mData;
private Node mParent;
private Node mLeft;
private Node mRight;
}
}
Explanation / Answer
package essaydemo;
public class BST {
private Node mRoot;
public BST()
{
Node mRoot = null;
}
public void insert(String key)
{
mRoot = insertRec(mRoot, key);
}
Node insertRec(Node node, String key) {
/* If the tree is empty, return a new node */
if (node == null) {
node = new Node(key);
return node;
}
/* Otherwise, recur down the tree */
if (key.compareTo(node.mData) < 0)
{
node.mLeft = insertRec(node.mLeft, key);
node.mLeft.mParent = node.mLeft;
}
else if (key.compareTo(node.mData) > 0)
{
node.mRight = insertRec(node.mRight, key);
node.mRight.mParent = node.mRight;
}
/* return the (unchanged) node pointer */
return node;
}
private class Node
{
public Node(String data)
{
mData = data;
mParent = null;
mLeft = mRight = null;
}
private String mData;
private Node mParent;
private Node mLeft;
private Node mRight;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.