Function doesn't return default value - c++

Here is my code:
bool BinarySearchTree::CheckIfTreeIsBinary(){
bool isBinary=true;
isBinary=CheckIfTreeIsBinaryPrivate(root); // So if my tree is binary, this function does not return anything
// and isBinary should remain true, but it is false.
return isBinary;
}
bool BinarySearchTree::CheckIfTreeIsBinaryPrivate(nodePtr Ptr){
if(Ptr->left!=NULL){
CheckIfTreeIsBinaryPrivate(Ptr->left);
}
if(Ptr->left!=NULL){
if(Ptr->data<Ptr->left->data)
return false; // possibility 1 to return false
}
if(Ptr->right!=NULL){
if(Ptr->data>Ptr->right->data)
return false; // possibility 2 to return false
}
if(Ptr->right!=NULL){
CheckIfTreeIsBinaryPrivate(Ptr->right);
}
}
In my function CheckIfTreeIsBinary, I have set boolean isBinary to true for default value. After that, isBinary is assigned to function CheckIfTreeIsBinaryPrivate, which will not return anything if the tree is binary.
The problem is that function CheckIfTreeIsBinaryPrivate doesn't return anything if the tree is binary, but in the end, isBinary is false.

The problem is that CheckIfTreeIsBinaryPrivate does not have an explicit return value on all program control paths.
That means that the behaviour of your program is undefined.
Your compiler will warn you of this, and it's your job to heed those warnings.

Your recursive logic is incorrect. All paths in a function should return a value and you should always check the return value of recursive calls to CheckIfTreeIsBinaryPrivate. There's no concept of 'a value remaining the same'. Here's what I think you are trying to achieve, but it's quite complicated.
bool BinarySearchTree::CheckIfTreeIsBinaryPrivate(nodePtr Ptr) {
return
// check the left sub tree is ok
(Ptr->left == NULL || // NULL is ok OR
(Ptr->data >= Ptr->left->data && // data >= left->data && left is ok
CheckIfTreeIsBinaryPrivate(Ptr->left))) &&
// and check the right sub tree is ok
(Ptr->right == NULL || // NULL is ok OR
(Ptr->data <= Ptr->right->data && // data <= right->data && right is ok
CheckIfTreeIsBinaryPrivate(Ptr->right)));
}

I think I see where your misunderstanding is; you're expecting isBinary to be updated only if CheckIfTreeIsBinaryPrivate returns a value.
That's not how it works - a function that has a non-void return type must always return something.
If the function doesn't explicitly return anything - for instance, by reaching the end of the function - the program has undefined behaviour.
There is no way for you to determine whether a function returned anything or not, and you must return something on every path through the function.
You can do this with one big expression,
bool BinarySearchTree::isBST(nodePtr Ptr){
return Ptr == nullptr
|| ( (Ptr->left == nullptr || (Ptr->left->data < Ptr->data && isBST(Ptr->left)))
&& (Ptr->right == nullptr || (Ptr->right->data > Ptr->data && isBST(Ptr->right))));
}
or piece by piece:
bool BinarySearchTree::isBST(nodePtr Ptr){
// An empty tree is a BST.
if (Ptr == nullptr)
return true;
// If the left subtree is not a BST, neither is the entire tree.
else if (Ptr->left != nullptr && (Ptr->left->data > Ptr->data || !isBST(Ptr->left)))
return false;
// If the right subtree is not a BST, neither is the entire tree.
else if (Ptr->right != nullptr && (Ptr->right->data < Ptr->data || !isBST(Ptr->right)))
return false;
// All tests passed.
else
return true;
}

Add one more base condition in CheckIfTreeIsBinaryPrivate() to set true,
because once you assign isBinary to CheckIfTreeIsBinaryPrivate() it will set false by default, and you need a return value to get true.

Related

Issue with function to check if tree is a BST

So I have a function to check if a tree is a bst(if every node only has smaller values on its left and larger values on its right). Every other function works and the problem is with this one (second one just calls helper). I think the issue has something to do with the recursive call root-left hitting null but I am not sure and even if it is not sure how to fix. Can add more code as needed. Any help is appreciated.
visual studio error i get is : R00t -> left was nullptr
other compiler: segmentation fault core dumped.
bool isBSThelper(TreeNode* R00t)
{
if (R00t == NULL)
return true;
//if (R00t->left != NULL && (R00t->info < R00t->left->info))
if (R00t->info < R00t->left->info)
return false;
//if (R00t->right != NULL && (R00t->info < R00t->right->info))
if (R00t->info > R00t->right->info)
return false;
return isBSThelper(R00t->left) && isBSThelper(R00t->right);
}
bool TreeType::isBST() const
{
return isBSThelper(root);
}
According to your comment
even with if (R00t->left != NULL || R00t->right != NULL) error persists
the problem would persist. Let me rewrite and iterate from there (since I can't comment to ask for clarification -new user). If your code was like
bool isBSThelper(TreeNode* R00t) {
if ( R00t == NULL )
return true;
if ( R00t->left != NULL || R00t->right != NULL ) {
if ( R00t->info < R00t->left->info )
return false;
if ( R00t->info < R00t->right->info )
return false;
}
return isBSThelper(R00t->left) && isBSThelper(R00t->right);
}
then you would potentially still encounter the same problem, since the expression
if (R00t->left != NULL || R00t->right != NULL) {
would still make this expression with values
R00t->left != NULL
but
R00t->right == NULL
evaluate to true.
One solution might be
To make sure R00T->left and R00t->right are either valid (pointing to a node) or NULL (preferably nullptr if you are using C++)
And code like this:
bool isBSThelper( TreeNode* R00t ) {
if ( R00t == NULL )
return true;
if ( R00t->left != NULL && R00t->info > R00t->left->info )
return false;
if ( R00t->right!= NULL && R00t->info > R00t->right->info )
return false;
return isBSThelper( R00t->left ) && isBSThelper( R00t->right );
}
And the problem would be no more. (1) is critical.
An additional note: Your code does not check
if (R00t->left != NULL && R00t->right!= NULL && R00t->left->info < R00t->right->info)
return false;
which is another property of a Binary Search Tree (or obviously using ">" instead of "<" here as you see fit).

return does not stop function, Recursive function issue? (programming exercise, Dynamic Programming, Levenshtein Back-trace)

the printOptimalAlignment function is misbehaving. goto and return will not exit when the function reaches location (1,1)... where it should end, no crash and it stops at seemingly an arbitrary location of (6,6)... because for some reason it increments at the end of the function even though there is no increment-er for the values int yL, int xL, (but I don't follow why it calls itself if it gets to the end of the function without any "hits" on the if statements.
Full code:
https://repl.it/#fulloutfool/Edit-Distance
void printOptimalAlignment(int** arr, string y, string x,int yL, int xL){
int I_weight=1, D_weight=1, R_weight=1;
bool printinfo_allot = 1,printinfo = 1;
if(printinfo_allot){
cout<<"Location: "<<"("<<xL<<","<<yL<<")"<<"-------------------------------\n";
cout<<"Same check Letters: "<<x[xL-2]<<","
<<y[yL-2]<<"("<<(x[xL-2] == y[yL-2])<<")"<<"\n";
cout<<"LL: "<<"("<<xL-1<<","<<yL<<")"
<<":"<<arr[yL][xL-1]
<<":"<<(arr[yL][xL-1]+I_weight)
<<":"<<(arr[yL][xL])
<<":"<<(((arr[yL][xL-1]+I_weight) == arr[yL][xL])==1)
<<":"<<(yL>=1 && xL>=1)<<"\n";
cout<<"xL state:"<<((&x[xL]))<<":"<<(x[xL-1])<<"\n";
cout<<"yL state:"<<((&y[yL]))<<":"<<(y[yL-1])<<"\n";
string tx = &x[xL];
cout<<x.length()<<","<<(tx.length()+1)<<"\n";
}
string tx = &x[xL]; // slopy hotfix
if(x.length()==(tx.length()+1)){
cout<<"return functionality not working?-=-=-=-=-=-=-=-=\n";
cout<<"-> Prep last, current distance = "<<arr[yL][xL] <<"\n";
return;
//printOptimalAlignment(arr,y,x,yL-1,xL-1);
//cant use this goto... but where does it go?
//goto because_Im_a_terrible_person;
throw "how?... breaking rules... make it stop";
}
if(yL>=1 && xL>=1 && (x[xL-2] == y[yL-2]) == 1){
if(printinfo){
cout<<"-> Same (same char), current distance = "<<arr[yL][xL] <<"\n";
}
printOptimalAlignment(arr,y,x,yL-1,xL-1);
}
if(yL>=1 && xL>=1 && (arr[yL-1][xL-1] == arr[yL][xL])){
if(printinfo){
cout<<"-> Swap (same int), current distance = "<<arr[yL][xL] <<"\n";
if(arr[yL-1][xL-1]==0)cout<<"---this is last---\n";
}
printOptimalAlignment(arr,y,x,yL-1,xL-1);
}
if(yL>0 && xL>0 && (arr[yL-1][xL]+D_weight == arr[yL][xL])){
if(printinfo){
cout<<"-> Delete, current distance = "<<arr[yL][xL]<<"\n";
}
printOptimalAlignment(arr,y,x,yL-1,xL);
}
//really weird ((yL>1 && xL>1) && (((arr[yL][xL-1]+I_weight) == arr[yL][xL])==1))
//not true if it is?
bool seperate = (((arr[yL][xL-1]+I_weight) == arr[yL][xL])==1);
if(yL>=1 && xL>=1){
if((((arr[yL][xL-1]+I_weight) == arr[yL][xL])==1) && (true)){
if(printinfo){
cout<<"-> Insert, current distance = "<<arr[yL][xL]<<"\n";
cout<<"Next Location1: "<<"("<<xL-1<<","<<yL<<")"<<"\n";
}
printOptimalAlignment(arr,y,x,yL,xL-1);
return;
//how does it get here... also return gets ignored... prob another stack issue
cout<<"insert function broke?????? # (1,1) ???????????????\n";
//return;
}
}
return;
cout<<"END... Hopefully.. if you see this Something went wrong\n";
because_Im_a_terrible_person:
cout<<"QUIT\n";
}
I suspect your problem is that your function calls itself and you don't appear to be taking into account what should happen next after that call to itself finishes. So you get to your finish condition where you say the return doesn't work, but it does... it just returns to where you left off in the previous call to printOptimalAlignment, which still might do something before returning to its caller, and so on. You have three different sites where you recursively call printOptimalAlignment that aren't immediately followed by a return statement, and at any of these it might be that the code will continue and trigger another of your conditional blocks.

No return evaluation in nested if

After watching carefully the following code I can't see why the compiler is warning me with "warning: control reaches end of non-void function".
bool Foam::solidMagnetostaticModel::read()
{
if (regIOobject::read())
{
if (permeabilityModelPtr_->read(subDict("permeability")) && magnetizationModelPtr_->read(subDict("magnetization")))
{
return true;
}
}
else
{
return false;
}
}
I can't see where is the problem, the else statement should care for returning false in every case which the first if is not true.
Trace the code path when regIOobject::read() is true, but either of permeabilityModelPtr_->read(subDict("permeability")) or magnetizationModelPtr_->read(subDict("magnetization")) is false. In that case, you enter the top if block (excluding the possibility of entering its attached else block), but then fail to enter the nested if block:
bool Foam::solidMagnetostaticModel::read()
{
if (regIOobject::read())
{
// Cool, read() was true, now check next if...
if (permeabilityModelPtr_->read(subDict("permeability")) && magnetizationModelPtr_->read(subDict("magnetization")))
{
return true;
}
// Oh no, it was false, now we're here...
}
else
{
// First if was true, so we don't go here...
return false;
}
// End of function reached, where is the return???
}
The minimalist fix is to just remove the else { } wrapping, so any fallthrough ends up at return false;:
bool Foam::solidMagnetostaticModel::read()
{
if (regIOobject::read())
{
// Cool, read() was true, now check next if...
if (permeabilityModelPtr_->read(subDict("permeability")) && magnetizationModelPtr_->read(subDict("magnetization")))
{
return true;
}
// Oh no, it was false, now we're here...
}
// Oh, but we hit return false; so we're fine
return false;
}
Alternatively, avoid specifically mentioning true or false at all, since your function is logically just a result of anding three conditions together:
bool Foam::solidMagnetostaticModel::read()
{
// No need to use ifs or explicit references to true/false at all
return regIOobject::read() &&
permeabilityModelPtr_->read(subDict("permeability")) &&
magnetizationModelPtr_->read(subDict("magnetization"));
}
The nested if is the problem.
When that branch is not taken, there is no other paths to take
the else statement should care for returning false in every case which the first if is not true.
Correct, but what if the first if condition is true, but the second if condition is not?
That is: What if regIOobject::read() returns true, but permeabilityModelPtr_->read(subDict("permeability")) returns false?
Then the flow of control enters the first if block, does not return, but does not enter the else block (because the first condition was true), so it just falls off the end of the function without hitting a return statement.
If you want the else { return false; } part to apply to either condition, you could just naively copy/paste it:
if (COND1) {
if (COND2) {
return true;
} else {
return false;
}
} else {
return false;
}
But that's quite a bit of code duplication. A better solution is to replace the nested if by a single condition:
if (COND1 && COND2) {
return true;
} else {
return false;
}
There's still some duplication: Both branches consist of a return statement followed by some expression.
We can factor out the common parts (return) and push the condition into the expression:
return COND1 && COND2 ? true : false;
But ? true : false is redundant: If the condition is true, evaluate to true, else evaluate to false? Well, that's just what the condition itself does:
return COND1 && COND2;
Or with your concrete expressions:
return regIOobject::read()
&& permeabilityModelPtr_->read(subDict("permeability"))
&& magnetizationModelPtr_->read(subDict("magnetization"));

Why is the IF (A || B) condition evaluated TRUE when one of its condition is FALSE?

private void case1(Tree t, Tree root) {
//System.out.println(root.left != t);
if (root.left != t || root.right != t)
case1(t, (root.value > t.value) ? root.left : root.right);
else {
if (root.left == t)
root.left = null;
else
root.right = null;
}
Why is the first IF condition evaluated TRUE even when root.left is actually equal to 't'? I have verified with print to console and the first condition does come out to be false. So the IF condition should be false, but the statement is still evaluated. The entire code is pretty big; I can provide more snippets if necessary.
Use && as || is for (OR) operator as if even one statement is true it will return true and in case of (AND) the both statements in if must be true only then it will return true.

C++ Linkedlist simple question

I'm trying to check if an entity exists in a given linkedlist. This is my code:
bool LinkedList::existByID(int ID)
{
//create node to search through the list
Node * helpNode;
//start it at the top of the list
helpNode = head;
if (head == NULL)
{
return false;
}
//while the item has not yet been found
while ((helpNode->data->indicatedEntity->getID() != ID) && (helpNode->data != NULL))
{
if (helpNode->data->indicatedEntity->getID() == ID)
{
//return true - the data exists
return true;
}
else
//if the data has not been found, move on
helpNode=helpNode->next;
}
//if the data has not been found and the end of the
//list has been reached, return false - the item does
//not exist
return false;
}
From the line I marked as the "problem line", the part of the if statement
(helpNode->data != NULL)
I get error CXX0017 (symbol "" not found) and error CXX0030 (expression cannot be evaluated).
This code works if there are no entities in the linkedlist - in other words, if the head is null.
The Node constructor looks like this:
LinkedList::Node::Node()
{
next=NULL;
data=NULL;
}
I've also tried it with the line:
(helpNode != NULL)
and Node constructor
LinkedList::Node::Node(){}
All combinations return the same errors. Any suggestions?
Firstly I recommend fixing a few things with your code.
In your loop you check the data member of helpNode before testing to see if helpNode is actually valid. Imagine you are on the last node - and at the end of the while the following executes - now what gets checked at the top?
helpNode=helpNode->next;
Secondly, once you've checked for helpNode, next you should check that data is valid before checking attributes of data, what if data is NULL?
And now think about what your loop is checking, it's checking that getID() != ID, and yet inside the loop you are testing for the ID, getID() == ID? does that make sense?
I recommend that in your loop, you just check that the next node and data exists, and then within the loop check that the ID matches, and return if true.
Well the line
while ((helpNode->data->indicatedEntity->getID() != ID) && (helpNode->data != NULL))
might be a problem if data is NULL, because then you would be trying to access NULL->indicatedEntity
further if indicatedEntity is NULL, then you are trying to access NULL->getID()
you can rewrite it to
while (helpNode->data != NULL && helpNode->data->indicatedEntity != NULL && helpNode->data->indicatedEntity->getID() != ID)
which doesnt look nice, but it does ensure your pointers are not null before trying to access them.