103 lines
3.0 KiB
Java
103 lines
3.0 KiB
Java
package labBST;
|
|
|
|
import java.io.BufferedReader;
|
|
import java.io.FileReader;
|
|
import java.io.IOException;
|
|
|
|
class Node {
|
|
int val;
|
|
Node left;
|
|
Node right;
|
|
Node parent;
|
|
}
|
|
|
|
public class Assignment {
|
|
public enum TraversalOrder {
|
|
InOrderTrav, PreOrderTrav, PostOrderTrav
|
|
}
|
|
|
|
public static class BST {
|
|
private Node root;
|
|
|
|
public BST() {
|
|
root = null;
|
|
}
|
|
|
|
public void insert(int toInsert) {
|
|
// Insert the provided element into the tree
|
|
}
|
|
|
|
public void delete(int toDelete) {
|
|
// Delete the provided element from the tree
|
|
}
|
|
|
|
|
|
public void print(TraversalOrder order) {
|
|
switch (order) {
|
|
case InOrderTrav:
|
|
inOrder(root);
|
|
break;
|
|
case PreOrderTrav:
|
|
preOrder(root);
|
|
break;
|
|
case PostOrderTrav:
|
|
postOrder(root);
|
|
break;
|
|
}
|
|
}
|
|
|
|
private void inOrder(Node curr) {
|
|
// Print the elements in the tree one one each line
|
|
System.out.println(curr.val);
|
|
}
|
|
|
|
private void preOrder(Node curr) {
|
|
// Print the elements in the tree one one each line
|
|
System.out.println(curr.val);
|
|
}
|
|
|
|
private void postOrder(Node curr) {
|
|
// Print the elements in the tree one one each line
|
|
System.out.println(curr.val);
|
|
}
|
|
}
|
|
|
|
public static void run(String inputPath) {
|
|
try (BufferedReader br = new BufferedReader(new FileReader(inputPath))) {
|
|
|
|
BST bst = new BST();
|
|
while (true) {
|
|
String instruction = br.readLine().trim();
|
|
if (instruction.length() < 1 || instruction.charAt(0) == 'e') {
|
|
break;
|
|
} else if (instruction.charAt(0) == 'i') {
|
|
int element = Integer.parseInt(instruction.substring(1));
|
|
bst.insert(element);
|
|
} else if (instruction.charAt(0) == 'd') {
|
|
int element = Integer.parseInt(instruction.substring(1));
|
|
bst.delete(element);
|
|
} else if (instruction.charAt(0) == 'o') {
|
|
String orderType = instruction.substring(1);
|
|
if (orderType.equals("in")) {
|
|
bst.print(TraversalOrder.InOrderTrav);
|
|
} else if (orderType.equals("pre")) {
|
|
bst.print(TraversalOrder.PreOrderTrav);
|
|
} else if (orderType.equals("post")) {
|
|
bst.print(TraversalOrder.PostOrderTrav);
|
|
} else {
|
|
System.out.println("Unknown Traversal Type: " + orderType);
|
|
}
|
|
} else {
|
|
System.out.println("Unknown instruction: " + instruction);
|
|
}
|
|
}
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
run("");
|
|
}
|
|
}
|