I have looked into tree traversal methods, but most of them use void modifiers and just printed the traversal sequence. Instead, is there a way to make a list of the sequence using recursion in Java? The starter code is below. Since preorder is List<T>, it should return a list, but global variables are not allowed. Then, there should be a list instance within the preorder method, but because it is recursive, the list will be created repetitively as well. I am stuck. Could someone versed in algorithm and Java help me with this?
public class Traversals<T extends Comparable<? super T>> {
//no global variables allowed
public List<T> preorder(TreeNode<T> root) {
// CODE HERE.
}
}
public class TreeNode<T extends Comparable<? super T>> {
private T data;
private TreeNode<T> left;
private TreeNode<T> right;
TreeNode(T data) {
this.data = data;
}
T getData() {
return data;
}
TreeNode<T> getLeft() {
return left;
}
TreeNode<T> getRight() {
return right;
}
void setData(T data) {
this.data = data;
}
void setLeft(TreeNode<T> left) {
this.left = left;
}
void setRight(TreeNode<T> right) {
this.right = right;
}
}
i could do It iteratively, but I do not know how to do recursively.