I'm supposed to traverse a Binary Seach Tree as preorder, inorder and postorder and insert the values into an Object[] in Java. I honestly have no clue how to do this and I need some advice.
My function:
public Object[] traversePreOrder()
All I need are basically some ideas or hints on how to complete this task. If I traverse a tree as preorder Object[0] is obviously the value of the root. Then I continue in the left tree and insert the most left values in my array. Next I insert the right child of the most left node and continue with the parent of both nodes if the right node has no children.
But my method can't remember which values have already been checked and inserted. I also thought of traversing in postorder, putting each element onto an stack and push each element onto my array, but I've got limits to my knowledge on how to implement this.
Help!
Here's what is in my opinion already correct:
@Override
public Object[] traversePreOrder() {
Object[] preOrderArray = new Object[elements];
if (elements == 0) {
return preOrderArray;
}
return preOrderArray;
}
The gap has to be filled obviously.
Additionally I have as basic methods and constructors:
BinarySearchTreeNode(T value, BinarySearchTreeNode<T> left,
BinarySearchTreeNode<T> right) {
this.value = value;
this.left = left;
this.right = right;
}
BinarySearchTreeNode(T value) {
this(value, null, null);
}
BinarySearchTreeNode<T> getLeft() {
return left;
}
void setLeft(BinarySearchTreeNode<T> left) {
this.left = left;
}
BinarySearchTreeNode<T> getRight() {
return right;
}
void setRight(BinarySearchTreeNode<T> right) {
this.right = right;
}
T getValue() {
return value;
}
void setValue(T value) {
this.value = value;
}