Question: package timedlab; // This is identical to the BinaryTree from class // but you have some methods to fill out public class BinaryTree { private
package timedlab;
// This is identical to the BinaryTree from class // but you have some methods to fill out public class BinaryTree
public BinaryTree() { this.root = null; //this.size = 0; } //////////// // Problems begin here! // Complete the method bodies where directed. // you don't have to write new methods or change the method signature ///////////
// Problem Tree 1 // 25 points // finish this method, printSortedTree // It will print out all the items stored in the tree // it will print them all out in sorted order.
// The recursive method that prints out the items in the tree // or subtree that starts at root. // Remember, the local variable root here is not necessarily THE root of the whole tree
public static
}
// Problem Tree 2 // 25 points // finish this method, which counts the number of Strings in the tree // which begin with the string prefix // Strings have a .startsWith(String) method to make this easy
// it's a recursive like above // you return an int here, so you don't need to print anything out public static int countStrings(Node
return -1; // replace this }
///////////////////// public int size() {
return this.size(this.root); }
private int size(Node
//int mySize = 1; //int leftSize = size(root.left); //int rightSize = size(root.right); return 1 + size(root.left)+ size(root.right); }
public void add(E item) { this.root = add(this.root, item);
}
private Node
}
public void remove(E item) { this.root = remove(this.root, item); }
private Node
// case 1, root is leaf if (root.left == null && root.right == null) { return null; } // case 2, root has only left child else if (root.left != null && root.right == null) { return root.left; } else if (root.left == null && root.right != null) { return root.right; } else { Node
if (rootOfLeftSubtree.right == null) { root.item = rootOfLeftSubtree.item; root.left = rootOfLeftSubtree.left; return root; } else { parentOfPredecessor = rootOfLeftSubtree; Node
predecessor = current; root.item = predecessor.item; parentOfPredecessor.right = predecessor.left; return root;
} }
}
}
public boolean contains(E item) { return contains(this.root, item); }
private boolean contains(Node
}
public String toString() { StringBuilder sb = new StringBuilder(); preOrderTraverse(root, 1, sb); return sb.toString(); }
private String toString(Node
output += root.item + " "; output += toString(root.left);
output += toString(root.right); return output;
}
private void preOrderTraverse(Node
private static class Node
public Node(E item) { this.item = item; }
public String toString() { return item.toString(); } }
public static void main(String[] args) { BinaryTree
printSortedTree(tree.root);
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
