From 3b6c546cd4f0f76912f41c97e571af7aab83e935 Mon Sep 17 00:00:00 2001 From: Oshgnacknak Date: Sat, 4 Sep 2021 16:23:38 +0200 Subject: [PATCH] Implement clone and invert --- .../exam/prep/tree/OrderedTreeProcessor.java | 2 +- ...cursiveOrderedBinaryTreeNodeProcessor.java | 24 ++++++++++++++++--- .../prep/tree/OrderedTreeProcessorTest.java | 24 +++++++++++++++++++ 3 files changed, 46 insertions(+), 4 deletions(-) diff --git a/src/aud/exam/prep/tree/OrderedTreeProcessor.java b/src/aud/exam/prep/tree/OrderedTreeProcessor.java index 54bdf4b..4e5579f 100644 --- a/src/aud/exam/prep/tree/OrderedTreeProcessor.java +++ b/src/aud/exam/prep/tree/OrderedTreeProcessor.java @@ -43,7 +43,7 @@ public interface OrderedTreeProcessor { T leftmostNodeInRightSubtree(T t); - T invert(T t); + void invert(T t); T clone(T t); diff --git a/src/aud/exam/prep/tree/RecursiveOrderedBinaryTreeNodeProcessor.java b/src/aud/exam/prep/tree/RecursiveOrderedBinaryTreeNodeProcessor.java index bb2a741..c4bcbcc 100644 --- a/src/aud/exam/prep/tree/RecursiveOrderedBinaryTreeNodeProcessor.java +++ b/src/aud/exam/prep/tree/RecursiveOrderedBinaryTreeNodeProcessor.java @@ -300,13 +300,31 @@ public class RecursiveOrderedBinaryTreeNodeProcessor extends OrderedBinaryTre } @Override - public BinaryTreeNode invert(BinaryTreeNode tree) { - return null; + public void invert(BinaryTreeNode tree) { + if (tree == null) { + return; + } + + invert(tree.left); + invert(tree.right); + + var t = tree.left; + tree.left = tree.right; + tree.right = t; } @Override public BinaryTreeNode clone(BinaryTreeNode tree) { - return null; + if (tree == null) { + return null; + } + + var t = new BinaryTreeNode(); + t.left = clone(tree.left); + t.right = clone(tree.right); + t.key = tree.key; + + return t; } @Override diff --git a/test/aud/exam/prep/tree/OrderedTreeProcessorTest.java b/test/aud/exam/prep/tree/OrderedTreeProcessorTest.java index 80c0ba1..2bb695e 100644 --- a/test/aud/exam/prep/tree/OrderedTreeProcessorTest.java +++ b/test/aud/exam/prep/tree/OrderedTreeProcessorTest.java @@ -243,4 +243,28 @@ public abstract class OrderedTreeProcessorTest { assertIterableEquals(list, processor.iterate(t)); } } + + @ParameterizedTest + @ArgumentsSource(ListProvider.class) + void testThat_invertWorks(List list) { + T t = asTree(list); + processor.invert(t); + + var cmp = CMP.reversed(); + + assertTrue(processor.check(t, cmp)); + list.sort(cmp); + assertIterableEquals(list, processor.iterate(t)); + } + + @ParameterizedTest + @ArgumentsSource(ListProvider.class) + void testThat_cloneWorks(List list) { + T t = asTree(list); + t = processor.clone(t); + + assertTrue(processor.check(t, CMP)); + list.sort(CMP); + assertIterableEquals(list, processor.iterate(t)); + } } \ No newline at end of file