I'm new to recursion and I don't see why this function won't compile. It is apparently missing a return statement. From testing it also seems as though my return statements do not return?
// recursive search method
public BinaryTree<T> recursiveSearch(BinaryTree<T> t, T key) {
if (key.compareTo(t.getData()) < 0) {
if (t.getLeft() != null) {
recursiveSearch(t.getLeft(), key);
} else {
return null;
}
} else if (key.compareTo(t.getData()) > 0) {
if (t.getRight() != null) {
recursiveSearch(t.getRight(), key);
} else {
return null;
}
} else if (key.compareTo(t.getData()) == 0) { // key is found
return t;
} else { // not in binary tree
return null;
}
}
The problem is on the lines inside the if branches that make recursive calls.
Your code will behave correctly when it reaches any of your else branches, because all of them have return null. If code takes one of the if branches, however, the control would reach the end of your method without hitting a return. The fix is simple - add the missing returns:
return recursiveSearch(t.getRight(), key);
Yes, it is missing a return statement for the recursion statements.
public BinaryTree<T> recursiveSearch(BinaryTree<T> t, T key)
{
if (key.compareTo(t.getData())<0){
if (t.getLeft() != null) {
recursiveSearch(t.getLeft(), key); // This case doesn't return anything
} else { return null;}
} else if (key.compareTo(t.getData())>0) {
if (t.getRight() != null) {
recursiveSearch(t.getRight(), key); // This case doesn't return anything
} else {return null;}
} else if (key.compareTo(t.getData())==0){ // key is found
return t;
} else {
//not in binary tree
return null;
}
}
I dont know your program logic, but if I have to guess, you might wanna add a return statement to the recursive calls. Like so,
return recursiveSearch(t.getLeft(), key);
and
return recursiveSearch(t.getRight(), key);
Related
This is what I've tried:
private static ApplicationGroup fetchDashboardParamInfo(List<ApplicationGroup> applicationGroup, String uniqueId) {
ApplicationGroup dashParamInfo = null;
for (ApplicationGroup a : applicationGroup) {
if (a.getUniqueId() == null || !a.getUniqueId().equals(uniqueId)) {
fetchDashboardParamInfo(a.getChildren(), uniqueId);
} else if (a.getUniqueId().equals(uniqueId)) {
dashParamInfo = a;
}
}
return dashParamInfo;
}
I'm simply running throug applicationGroup which is a list of application groups. It's actually a hierarchy of application groups. I'm trying to make the method recurse if the "if"-statement is true, with a.getChildren() as the new a. If the "else if"-statement is true, dashParamInfo should simply be equal to whatever a is at that point, and then the method should return dashParamInfo without further looping. The problem I have is that when the "if"-statement becomes true, it doesn't recurse, it goes inside the statement but then it just goes to return and ends the method right away. What am I doin wrong?
If the correct answer is not found in the current applicationGroup you need to recurse deeper. But if you recurse you need to check if the recurrent call has found what you were looking for; if so, you need to return it.
private static ApplicationGroup fetchDashboardParamInfo(List<ApplicationGroup> applicationGroup, String uniqueId) {
for (ApplicationGroup a : applicationGroup) {
if (a.getUniqueId() == null || !a.getUniqueId().equals(uniqueId)) {
ApplicationGroup dashParamInfo = fetchDashboardParamInfo(a.getChildren(), uniqueId);
if (dashParamInfo != null)
return dashParamInfo;
} else if (a.getUniqueId().equals(uniqueId)) {
return a;
}
}
return null;
}
I think you are missing return before fetchDashboardParamInfo(a.getChildren(), uniqueId);
private static ApplicationGroup fetchDashboardParamInfo(List<ApplicationGroup> applicationGroup, String uniqueId) {
ApplicationGroup dashParamInfo = null;
for (ApplicationGroup a : applicationGroup) {
if (a.getUniqueId() == null || !a.getUniqueId().equals(uniqueId)) {
return fetchDashboardParamInfo(a.getChildren(), uniqueId);
} else if (a.getUniqueId().equals(uniqueId)) {
dashParamInfo = a;
break;
}
}
return dashParamInfo;
}
I have this homework problem and I have completed all methods except this one, isPerfectlyBalanced().
All my tests pass except one that should return false but instead returns true. I have attached my current code and the test that is failing. Any description on how to go about this or even let me know where my code is wrong is appreciated!
private boolean isPerfectlyBalanced(Node node) {
if (node == null) {
return true;
}
if(size(node.left) == size(node.right)) {
return true;
}
isPerfectlyBalanced(node.left);
isPerfectlyBalanced(node.right);
return false;
}
public boolean isPerfectlyBalancedS() {
// TODO
if (root == null) {
return true;
}
return isPerfectlyBalanced(root);
}
Here is my test that is failing:
assertFalse(set.isPerfectlyBalancedS());
Thank you!
My size method:
private int size(Node node){
if (node == null){
return 0;
} else {
return (size(node.left) + 1 + size(node.right));
}
}
public int size() {
// TODO
return size(root);
}
On the last line of the first method, you probably want to do this:
return (isPerfectlyBalanced(node.left) && isPerfectlyBalanced(node.right));
instead of
isPerfectlyBalanced(node.left);
isPerfectlyBalanced(node.right);
return false;
In your code, you dismiss the result of the isPerfectlyBalanced on the subtrees and always return false.
I'm working on Java Binary Search Tree, and I'm trying to use method findHelp() in find(). I'm expecting a return value of rt.getValue() (which is C2-112, as I print out right before return), but printing out findHelp() in help method returns null.
I couldn't find similar error online, so can someone help me figure out, or give a link to a similar issue?
Here is my code
private E findHelp(BinaryNode<Key, E> rt, Key k) {
int compare = k.compareTo(rt.getKey());
if (compare==0) {
System.out.println(rt.getValue()); // I'm getting C2-112 here
return rt.getValue(); // so I expect a return of C2-112
} else if (compare >0 ) {
if (rt.getRight() == null) {
return null;
} else {
findHelp(rt.getRight(), k);
}
} else {
if (rt.getLeft() == null) {
return null;
} else {
findHelp(rt.getLeft(), k);
}
}
return null;
} //
public E find(Key k) {
E tmp = findHelp(root, k);
System.out.println(tmp); // this prints null, not C2-112
return findHelp(root, k); // and so I return null
}
add a return before every findHelp(...)
I was reading about recursive methods in java ... I do not undserstand the base condition of the recursive method ... Here are two examples
public int weight() {
return weight(root);
}
/ * Returns the weight of the tree where n is the root. * /
private int weight(Node n) {
if (n == null) {
return 0;
} else if (n.left == null) { // då är n.right också null
return n.data;
} else {
return weight(n.left) + weight(n.right);
}
}
public boolean isMobile() {
if (root == null) {
return true;
} else {
return isMobile(root);
}
}
/ * Returns true if the tree where n is the root of a mobile. * /
private boolean isMobile(Node n) {
if (n.left == null) { // då är n.right också null
return true;
} else {
return isMobile(n.left) && isMobile(n.right) &&
weight(n.left) == weight(n.right);
}
}
My wonder : in the weight() method why do not we do like this :
public int weight() {
if (root == null) {
return 0;
} else {
return weight(root);
}
}
As you can see the base condition in the isMobile() method is directly under it but the base condition in the weight() method is under the private method ..
When it is possible to write the base condition of the recursive directly under it or in a separate private method ?
Thanks
EDIT :
public int weight() {
if (root == null) {
return 0;
} else {
return weight(root);
}
}
private int weight(Node n) {
if (n == null) {
return 0;
} else if (n.left == null) { // då är n.right också null
return n.data;
} else {
return weight(n.left) + weight(n.right);
}
}
in the weight() method why do not we do like this : [...]
The simple answer is because parameterless weight() overload of the method is not recursive, even though it relies on a recursive implementation that takes Node as its parameter. The base condition must be in the recursive method itself, because that is where the decision to stop calling itself must be made.
Despite being overloads of the same name, your two weight methods work together like this:
public int nonRecursiveWeight() {
return recursiveWeight(root);
}
private int recursiveWeight(Node n) {
...
}
The nonRecursiveWeight provides a nice public "front" for the recursive implementation recursiveWeight, hiding the node from the API users.
isMobile pair of methods follows the same arrangement: you have a recursive implementation, and a non-recursive "front" sharing the same name.
Base condition must be in the recursive method. The method weight() is not recursive as it is not calling itself. It is calling a recursive method weight(Node n) which has and must have base condition.
if (n == null) { return 0; }
Intention in the isMobile() and isMobile(Node n) is a bit different. The author probably wanted to check for root == null directly in isMobile() method to avoid double checks in recursive method but they can be rewritten like this:
public boolean isMobile() {
return isMobile(root);
}
private boolean isMobile(Node n) {
if ( n == null || n.left == null ) return true;
return isMobile(n.left) && isMobile(n.right) && weight(n.left) == weight(n.right);
}
Again isMobile(Node n) is recursive and isMobile() is not. The isMobile methods now look the same as weight methods. In general the rule is that the recursive methods are the ones which call themselves and they must have base condition which will terminate recursion.
Also please note that you do not need to write else if you have a return before that. For example:
boolean someMethod() {
if ( something ) {
return true;
} else {
return false;
}
}
Can be rewritten as:
boolean someMethod() {
if ( something ) {
// ...
return true;
}
// if something was true then the next piece of code will never get executed
// if was not true then the next piece of code will always execute
// ...
return false;
}
You probably meant if (root == null) in your re-write.
You still have to check in weight(Node) since it's recursive–why do it twice?
public static boolean isCompatibleForMultiplcation(final Matrix a, final Matrix b)
{
if (a == null)
{
throw new IllegalArgumentException("a cannot be null");
}
if (b == null)
{
throw new IllegalArgumentException("b cannot be null");
}
if(!(a.getNumberofColumns()== b.getNumberOfRows()))
{
return false;
}
else
{
return true;
}
}
I am getting a 'Conditional Logic can be removed argument in checkstyle for the following method. I cannot seem to figure out why... Can someone give me a pointer?
It is complaining about this part right here :
if(a.getNumberofColumns() != b.getNumberOfRows())
{
return false;
}
else
{
return true;
}
Whenever you see yourself writing code like this you can easily replace it with a single line by just returning the condition from the if statement:
return a.getNumberofColumns() == b.getNumberOfRows();
This statement will return true if the the number of columns for a and rows for b are equal, and false otherwise.