Add methods for traversing trees

This commit is contained in:
Manuel Thalmann 2022-10-18 13:46:36 +02:00
parent e5068eecc8
commit e47818c3fa
2 changed files with 47 additions and 7 deletions

View file

@ -68,8 +68,7 @@ public class SortedBinaryTree<T extends Comparable<T>> implements Tree<T> {
}
public Traversal<T> traversal() {
// TODO Implement
return null;
return new TreeTraversal<>(root);
}
protected int calcHeight(TreeNode<T> node) {

View file

@ -1,5 +1,8 @@
package ch.nuth.zhaw.exbox;
import java.util.Deque;
import java.util.LinkedList;
public class TreeTraversal<T extends Comparable<T>> implements Traversal<T> {
private final TreeNode<T> root;
@ -8,21 +11,59 @@ public class TreeTraversal<T extends Comparable<T>> implements Traversal<T> {
}
public void inorder(Visitor<T> vis) {
// TODO Implement
if (root.left != null) {
new TreeTraversal<>(root.left).inorder(vis);
}
vis.visit(root.getValue());
if (root.right != null) {
new TreeTraversal<>(root.right).inorder(vis);
}
}
public void preorder(Visitor<T> vis) {
// TODO Implement
vis.visit(root.getValue());
if (root.left != null) {
new TreeTraversal<>(root.left).preorder(vis);
}
if (root.right != null) {
new TreeTraversal<>(root.right).preorder(vis);
}
}
public void postorder(Visitor<T> vis) {
// TODO Implement
if (root.left != null) {
new TreeTraversal<>(root.left).postorder(vis);
}
if (root.right != null) {
new TreeTraversal<>(root.right).postorder(vis);
}
vis.visit(root.getValue());
}
@Override
public void levelorder(Visitor<T> vistor) {
// TODO Auto-generated method stub
Deque<TreeNode<T>> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode<T> node = queue.poll();
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
vistor.visit(node.getValue());
}
}
@Override