Skip to content

Commit

Permalink
#2 - traversal using nodes
Browse files Browse the repository at this point in the history
  • Loading branch information
obriensystems committed Feb 11, 2024
1 parent 91a54d7 commit ae0d399
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ public interface BinaryTree<T extends Comparable<? super T>> {
T getData();
boolean search(T value);
Integer depth();
List<T> inOrderTraversal();
List<T> inOrderTraversalHelper(List<T> list);

List<BinaryTree<T>> inOrderTraversal();
List<BinaryTree<T>> inOrderTraversalHelper(List<BinaryTree<T>> list);
List<BinaryTree<T>> inOrderTraversalOnlyLeft();
List<BinaryTree<T>> inOrderTraversalOnlyLeftHelper(List<BinaryTree<T>> list);
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,34 @@ public T getData() {
}

@Override
public List<T> inOrderTraversal() {
return inOrderTraversalHelper(new ArrayList<T>());
public List<BinaryTree<T>> inOrderTraversal() {
return inOrderTraversalHelper(new ArrayList<BinaryTree<T>>());
}

@Override
public List<T> inOrderTraversalHelper(List<T> list) {
public List<BinaryTree<T>> inOrderTraversalHelper(List<BinaryTree<T>> list) {
if(null != left)
left.inOrderTraversalHelper(list);
list.add(data);
list.add(this);
if(null != right)
right.inOrderTraversalHelper(list);
return list;
}

@Override
public List<BinaryTree<T>> inOrderTraversalOnlyLeft() {
return inOrderTraversalOnlyLeftHelper(new ArrayList<BinaryTree<T>>());
}

@Override
public List<BinaryTree<T>> inOrderTraversalOnlyLeftHelper(List<BinaryTree<T>> list) {
if(null != left)
left.inOrderTraversalOnlyLeftHelper(list);
list.add(this);
if(null != right)
right.inOrderTraversalOnlyLeftHelper(list);
return list;
}

@Override
public void add(T value) {
Expand Down Expand Up @@ -80,7 +95,7 @@ public boolean search(T value) {
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
inOrderTraversal().stream().forEach(i -> buffer.append(i).append(","));
inOrderTraversal().stream().forEach(i -> buffer.append(i.getData()).append(","));
return buffer.toString();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,14 @@ public class BinaryTreeTest {
@Test
public void testContructor() {
BinaryTree<Integer> tree = new BinaryTreeImpl<Integer>();
List<Integer> list = tree.inOrderTraversal();
assertNotNull(list);


// Add a list of numbers
List<Integer> numbersToInsert = Stream.of(8,16,32,64,48,2,128).collect(Collectors.toList());
tree.add(numbersToInsert);

List<BinaryTree<Integer>> list = tree.inOrderTraversal();
assertNotNull(list);

BinaryTree<Integer> subTree = tree.getRight();
assertNotNull(subTree);
Expand Down

0 comments on commit ae0d399

Please sign in to comment.