diff --git a/app/src/main/java/ch/nuth/zhaw/exbox/SortedBinaryTree.java b/app/src/main/java/ch/nuth/zhaw/exbox/SortedBinaryTree.java index f8b548f..3cc9f7a 100644 --- a/app/src/main/java/ch/nuth/zhaw/exbox/SortedBinaryTree.java +++ b/app/src/main/java/ch/nuth/zhaw/exbox/SortedBinaryTree.java @@ -68,8 +68,7 @@ public class SortedBinaryTree> implements Tree { } public Traversal traversal() { - // TODO Implement - return null; + return new TreeTraversal<>(root); } protected int calcHeight(TreeNode node) { diff --git a/app/src/main/java/ch/nuth/zhaw/exbox/TreeTraversal.java b/app/src/main/java/ch/nuth/zhaw/exbox/TreeTraversal.java index 8037739..cf9990f 100644 --- a/app/src/main/java/ch/nuth/zhaw/exbox/TreeTraversal.java +++ b/app/src/main/java/ch/nuth/zhaw/exbox/TreeTraversal.java @@ -1,5 +1,8 @@ package ch.nuth.zhaw.exbox; +import java.util.Deque; +import java.util.LinkedList; + public class TreeTraversal> implements Traversal { private final TreeNode root; @@ -8,21 +11,59 @@ public class TreeTraversal> implements Traversal { } public void inorder(Visitor 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 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 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 vistor) { - // TODO Auto-generated method stub - + Deque> queue = new LinkedList<>(); + queue.add(root); + + while (!queue.isEmpty()) { + TreeNode node = queue.poll(); + + if (node.left != null) { + queue.add(node.left); + } + + if (node.right != null) { + queue.add(node.right); + } + + vistor.visit(node.getValue()); + } } @Override