if (getRoot() == null)
throw new IllegalArgumentException("tree is empty");
// detach left subtree and save in leftSubtree
LinkedBinaryTree leftSubtree = new LinkedBinaryTree();
leftSubtree.setRoot(getRoot().getLeftChild());
getRoot().setLeftChild(null);
return (BinaryTree) leftSubtree;
}
/**
* remove the right subtree
*
* @throws IllegalArgumentException
* when tree is empty
* @return removed subtree
*/
public BinaryTree removeRightSubtree() {
if (getRoot() == null)
throw new IllegalArgumentException("tree is empty");
// detach right subtree and save in rightSubtree
LinkedBinaryTree rightSubtree = new LinkedBinaryTree();
rightSubtree.setRoot(getRoot().getRightChild());
getRoot().setRightChild(null);
return (BinaryTree) rightSubtree;
}
/** preorder traversal */
public void preOrder(Method visit) {
LinkedBinaryTree.visit = visit;
thePreOrder(getRoot());
}
/** actual preorder traversal method */
static void thePreOrder(BinaryTreeNode t) {
if (t != null) {
visitArgs[0] = t;
try {
visit.invoke(null, visitArgs);
} // visit tree root
catch (Exception e) {
System.out.println(e);
}
thePreOrder(t.getLeftChild()); // do left subtree
thePreOrder(t.getRightChild()); // do right subtree
}
}
/** inorder traversal */
public void inOrder(Method visit) {
LinkedBinaryTree.visit = visit;
theInOrder(getRoot());
/** actual inorder traversal method */
static void theInOrder(BinaryTreeNode t) {
if (t != null) {
theInOrder(t.getLeftChild()); // do left subtree
visitArgs[0] = t;
try {
visit.invoke(null, visitArgs);
} // visit tree root
catch (Exception e) {
System.out.println(e);
}
theInOrder(t.getRightChild()); // do right subtree
}
}
/** postorder traversal */
public void postOrder(Method visit) {
LinkedBinaryTree.visit = visit;
thePostOrder(getRoot());
}
/** actual postorder traversal method */
static void thePostOrder(BinaryTreeNode t) {
if (t != null) {
thePostOrder(t.getLeftChild()); // do left subtree
thePostOrder(t.getRightChild()); // do right subtree
visitArgs[0] = t;
try {
visit.invoke(null, visitArgs);
} // visit tree root
catch (Exception e) {
System.out.println(e);
}
}
}
/** level order traversal */
public void levelOrder(Method visit) {
ArrayQueue q = new ArrayQueue(10);
BinaryTreeNode t = getRoot();
while (t != null) {
visitArgs[0] = t;
try {
visit.invoke(null, visitArgs);
} // visit tree root
catch (Exception e) {
System.out.println(e);
}
// put t's children on queue
if (t.getLeftChild() != null)
q.put(t.getL