Finish the parts labeled //Finish. Insertion of nodes into a binary search tree.
ID: 3764936 • Letter: F
Question
Finish the parts labeled //Finish. Insertion of nodes into a binary search tree. Please try first, as last answer had an illegal start of expression.
public class BinarySearchTreeNode {
int key;
BinarySearchTreeNode left;
BinarySearchTreeNode right;
BinarySearchTreeNode(int k) {
key = k;
left = null;
right = null;
}
void insert(int newKey) {
if(newKey<=key) {
//FINISH
} else {
//FINISH
}
}
@Override
public String toString() {
String leftString = "";
if(left!=null) leftString = left.toString();
String rightString = "";
if(right!=null) rightString = right.toString();
return leftString+" "+key+" "+rightString;
}
public static void main(String[] args) {
BinarySearchTreeNode root = new BinarySearchTreeNode(30);
System.out.println(root);
root.insert(40);
System.out.println(root);
root.insert(24);
System.out.println(root);
root.insert(58);
System.out.println(root);
root.insert(48);
System.out.println(root);
root.insert(26);
System.out.println(root);
root.insert(11);
System.out.println(root);
root.insert(13);
System.out.println(root);
}
}
Explanation / Answer
void insert(int newKey)
{
if(newKey<=key)
{
left.key = newKey;
if (left == null)
{
left = new BinarySearchTreeNode(newKey);
}
}
else
{
right.key = newKey;
if (right == null)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.