JAVA: Complete the following method removeLeaves() RECURSIVELY USING ONE HELPER
ID: 3878157 • Letter: J
Question
JAVA: Complete the following method removeLeaves() RECURSIVELY USING ONE HELPER FUNCTION.
public class MyIntSET {
private Node root;
private static class Node {
public final int key;
public Node left, right;
public Node(int key) { this.key = key; }
}
// remove all leaves from the original tree
// if you start with "41", then the result is the empty tree.
// if you start with "41 21 61", then the result is the tree "41"
// if you start with the BST "41 21 11 1", then the result is the tree "41 21 11"
// if you start with the BST "41 21 61 11", then the result is the tree "41 21"
// Hint: This requires that you check for "leafiness" before the recursive calls
public void removeLeaves() {
// TODO
}
Explanation / Answer
Node leafRemove(Node root)
{
if (root.left == null && root.right == null) {
root = null;
return null;
}
root.left = leafRemove(root.left);
root.right = leafRemove(root.right);
return root;
}
public void removeLeaves() {
root = leafRemove(root);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.