public void delete(int x) {
IntNode n1 = search(x);
if (n1 == null) {
System.out.println(x + " is not in the tree");
}
//n1 has two children:
else if (n1.getLeft() != null && n1.getRight() != null) {
IntNode n2 = n1.getLeft();
IntNode n3 = n1;
while (n2.getRight() != null) {
n3 = n2;
n2 = n2.getRight();
}
n1.setData(n2.getData());
if (n3.getRight() == n2) {
n3.setRight(n2.getLeft());
} else {
n3.setLeft(n2.getLeft());
}
}
// n1 is the root:
else if (n1 == root) {
if (n1.getRight() != null) {
root = n1.getRight();
} else {
root = n1.getLeft();
}
} else {
// need to find n1's parent
IntNode parent = root;
while (parent.getLeft() != n1 && parent.getRight() != n1) {
if (x > parent.getData()) {
parent = parent.getLeft();
} else {
parent = parent.getRight();
}
}
if (n1.getLeft() != null) {
if (parent.getLeft() == n1) {
parent.setLeft(n1.getLeft());
} else {
parent.setRight(n1.getLeft());
}
} else {
if (parent.getLeft() == n1) {
parent.setLeft(n1.getRight());
} else {
parent.setRight(n1.getRight());
}
}
}
}
What will be printed by this program? Write it on your memory picture. Run the program to check your answer, modify your picture if needed.
public class Lab9Prob2 {
public static void main(String [] args) {
int [] arr1 = {1, 2, 3};
int [] arr2 = {6, 7, 8};
m1(arr1, arr2);
System.out.println("after m1:");
print(arr1);
print(arr2);
m2(arr1, arr2);
System.out.println("after m2:");
print(arr1);
print(arr2);
}
public static void m1(int [] a, int [] b) {
for (int i = 0; i < a.length; ++i) {
int temp = a[i];
a[i] = b[i];
b[i] = temp;
}
System.out.println("in m1:");
print(a);
print(b);
// Memory picture 1
}
public static void m2(int [] a, int [] b) {
int [] temp = a;
a = b;
b = temp;
System.out.println("in m2:");
print(a);
print(b);
// Memory picture 2
}
public static void print(int [] items) {
// print array elements all on one line
for (int i = 0; i < items.length; ++i) {
System.out.print(items[i] + " ");
}
System.out.println();
}
}