gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
Write a recursive body for the following static, generic method that computes and…
- User
Write a recursive body for the following static, generic method that computes and returns the size of a given BinaryTree. You can use any of the BinaryTree methods except for the iterator and the size kernel method. Note that the BinaryTree must be restored, i.e., its outgoing value must be the same as its incoming value. 1 2 3 4 5 6 7 8 9 10 11 /**
- Returns the size of the given {@code BinaryTree}.
- @param
-
code
the type of the {@code BinaryTree} node labels - @param t
-
code
the {@code BinaryTree} whose size to return - @return the size of the given {@code BinaryTree}
- @ensures size = |t| */ public static int size(BinaryTree t) {...} Provide a second implementation of the size method above but this time make it an iterative (non-recursive) solution. You cannot use the size kernel method in your solution.
- Assistant
Recursive Solution:
codepublic static <T> int size(BinaryTree<T> t) { if (t.isEmpty()) { return 0; } else { return 1 + size(t.getLeft()) + size(t.getRight()); } }Iterative Solution:
codepublic static <T> int size(BinaryTree<T> t) { if (t.isEmpty()) { return 0; } int count = 0; Queue<BinaryTree<T>> queue = new LinkedList<>(); queue.add(t); while (!queue.isEmpty()) { BinaryTree<T> current = queue.poll(); count++; if (!current.getLeft().isEmpty()) { queue.add(current.getLeft()); } if (!current.getRight().isEmpty()) { queue.add(current.getRight()); } } return count; }