Find specific node height in tree c++ - c++

I am trying traverse over tree and check for specific (rel_name) and return his height, but my function traverse over "mother" branch and checks only fathers branch.
The result is that my program return exception() and core dumping.
how do I fix my function to not core dump and check mothers branch too?
string treeHeight(Person* root, string rel_name, int height){
height++;
if(root == nullptr) {
throw exception();
}
else if(root->name == rel_name) return to_string(height);
return treeHeight(root->father, rel_name, height);
return treeHeight(root->mother, rel_name, height);
}

Someone has already pointed out, but if your code reaches a leaf and goes a little bit further, according to your base case it would throw an exception and exit the program.
I revised your code a little bit:
int treeHeight(Person* root, const string& rel_name){
if(root == nullptr) {
return -1;
}
else if(root->name == rel_name) return 0;
int leftHeight = treeHeight(root->father, rel_name);
int rightHeight = treeHeight(root->mother, rel_name);
if (leftHeight == -1 && rightHeight == -1) {
return -1;
} else {
return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;
}
}
Hope it helps.

In your code , you are not allowing the code to go the mother node, its directly from the father node call and thus its not getting executed ahead.
Try this below :
string treeHeight(Person* root, string rel_name, int height){
height++;
if(root == nullptr) {
throw exception();
}
else if(root->name == rel_name) return to_string(height);
int person_height = treeHeight(root->father, rel_name, height);
if(person_height!=0) return height; ---------> You need to apply this check
return treeHeight(root->mother, rel_name, height);
}

Related

c++ how to get depth of a binary tree recursively

I wrote a code that suposed to return the depth of a binary tree from the root to the node who called the function. using recursive way but I faced a problem about how to count the number of times that the function gets called so I whould know how much convexity I passed. Someone know how can I do that?
int BSNode::getDepth(const BSNode& root) const
{
if (this != nullptr)
{
if (root.getData() > this->_data)
{
this->getDepth(*root.getRight());
}
else if (root.getData() < this->_data)
{
this->getDepth(*root.getLeft());
}
else if (root.getData() == this->_data)
{
// return the number that the function counted
}
}
else
{
return 0;
}
}
You should at least return something in every case. And when you arrive at the intended node (having the data you are looking for), then return 0. In all other cases, return what you get from recursion plus 1. If the value is not found then indeed -1 should be returned. And if this -1 is coming back from recursion, it should be returned like that also to the caller (without adding 1).
Here is the code adapted:
int BSNode::getDepth(const BSNode& root) const
{
int temp;
if (this != nullptr)
{
if (root.getData() > this->_data)
{
temp = this->getDepth(*root.getRight());
return temp == -1 ? -1 : temp + 1;
}
else if (root.getData() < this->_data)
{
temp = this->getDepth(*root.getLeft());
return temp == -1 ? -1 : temp + 1;
}
else if (root.getData() == this->_data)
{
return 0;
}
}
else
{
return -1;
}
}

Sorting linked list in C++ fails at runtime

void head_insert(DomesticPtr& head, string firstNameD, string lastNameD, string province, float cgpaD, int researchScoreD, int idD)
{
DomesticPtr temp_ptr;
DomesticPtr temp2;
temp_ptr= new DomesticStudent(head, firstNameD, lastNameD, province,cgpaD,researchScoreD,idD);
temp2 = head->getLink();
temp2==temp_ptr;
head=temp_ptr;
if (head->getLink() == NULL)
return;
else
{
bubblesort(head);
}
}
void bubblesort(DomesticStudent* head)
{
int rsd;
int cgpad;
int p;
DomesticPtr tempc, tempd, tempe;
tempd=head;
tempe= head->getLink();
{
while(tempd != NULL)
{
rsd=compareResearchScore(tempd, tempe);
if (rsd==1)
{
tempc=head;
head->next=head;
head=tempc;
}// if
else if (rsd==0)
{
cgpad= compareCGPA(tempe,tempd);
if (cgpad==1)
{
tempc=head;
head->next=head;
head=tempc;
}// if (cgpad[k]>cgpad[k+1])
else if(cgpad==0)
{
p=compareProvince(tempd,tempe);
if(p==1)
{
tempc=head;
head->next=head;
head=tempc;
}// if (p[k]>p[k+1])
}//
}// else if cgpad[k]
}// else if rsd[k]
// }
// }
tempd = tempe;
}
int compareResearchScore(DomesticPtr RSA, DomesticPtr RSB)
{
if (RSB == NULL || RSA==NULL )
{
return 0;
}
if (RSA->researchScoreD==RSB->researchScoreD) //compares if is the same for domesetic students returns value for bubble sort
{
return 0;
}
if (RSA->researchScoreD > RSB->researchScoreD)
{
return 1;
}
if (RSA->researchScoreD< RSB->researchScoreD)
{
return -1;
}
}
I'm trying to to have my linked list sorted every time a new node is inserted. It compiles but every time I try to run the program it is stuck on the point that I am trying to print my list. I have a destructor but no copy constructor or assignment operator.
The head_insert calls the sort function and the sort function calls the compare function to receive an integer output so that it can make a swap. I want to compare research, the cgpa, and then province. Any input would be much appreciated, this is for a project so I wouldn't like any blocks of code but if you could point me in the right direction or multiple directions.

Error: control may reach end of non-void function in C++

I cannot figure out why this error is happening: error: "control may reach end of non-void function" even when "else" statement is present at the end.
Here is the code:
bnode* binsert(bnode *h,int k){
bnode *temp=new bnode;
if(h==NULL)
{
temp->num=k;
temp->L=NULL;
temp->R=NULL;
h=temp;
return h;
}
else if(h->L==NULL && k<h->num)
{
temp->num=k;
temp->L=NULL;
temp->R=NULL;
h->L=temp;
return h;
}
else if(h->R==NULL && k>h->num)
{
temp->num=k;
temp->L=NULL;
temp->R=NULL;
h->R=temp;
return h;
}
else if(h->L!=NULL && k<h->num)
{
h->L=binsert(h->L,k);
}
else
{
h->R=binsert(h->R,k);
}
}
You need to return the results of recursive calls, it's not done automatically.
You can also simplify your code a bit by adding a constructor:
bnode::bnode(int v)
: num(v),
L(nullptr),
R(nullptr)
{
}
and since you're already handling the case of a null parameter, you don't need special cases for null children:
bnode* binsert(bnode *h,int k)
{
if(h == nullptr)
{
h = new bnode(k);
}
else if(k < h->num)
{
h->L = binsert(h->L, k);
}
else if(k > h->num)
{
h->R = binsert(h->R, k);
}
return h;
}
because this last 2 conditions:
else if(h->L!=NULL && k<h->num)
{
h->L=binsert(h->L,k);
}
else
{
h->R=binsert(h->R,k);
}
may occur and no return is given...
you need to be sure the function returns a value no matter what the condition evaluates....
else if(h->L!=NULL && k<h->num)
{
h->L=binsert(h->L,k);
}
else
{
h->R=binsert(h->R,k);
}
In the else if and else cases for your code, if you reach here, you do not return a value, and the behavior is undefined if you try to use this value.
You probably want to add a return h; in the two branches.

char changing after returned

This is an attempted solution of a problem on codefights: https://codefights.com/interview-practice/task/FwAR7koSB3uYYsqDp
My BFS function is not returning the correct character despite me printing right before the return and seeing the correct character in the console. It seems the chracter is being mutated for some reason. When I change the function signature to have a std::string return value, the program crashes. I have no clue what I'm doing wrong. Is it possibly due to lack of freeing pointers or something?
typedef struct proTree{
char value;
proTree* left;
proTree* right;
} proTree;
char BFS(std::vector<proTree*> vec, int currLevel, int level, int pos){
if (currLevel == level){
if (vec[pos-1]->value == 'E'){
return 'E';
} else {
return 'D';
}
}
std::vector<proTree*> newVec;
for (int i=0; i<vec.size(); i++){
newVec.push_back(vec[i]->left);
newVec.push_back(vec[i]->right);
}
BFS(newVec, currLevel+1, level, pos);
}
void createTree(proTree* root, int currLevel, int level){
if (currLevel == level) return;
proTree* eTree = new proTree();
eTree->value = 'E';
proTree* dTree = new proTree();
dTree->value = 'D';
if (root->value=='E'){
root->left = eTree;
root->right = dTree;
} else {
root->left = dTree;
root->right = eTree;
}
createTree(eTree, currLevel+1, level);
createTree(dTree, currLevel+1, level);
}
std::string findProfession(int level, int pos) {
proTree* eTree = new proTree();
eTree->value = 'E';
createTree(eTree, 0, level);
std::vector<proTree*> vec = {eTree};
char result = BFS(vec, 0, level, pos);
if (result == 'E'){
return "Engineer";
} else {
return "Doctor";
}
}
BFS does not return anything (actually returned value is undefined) because last function line is missing return and the value of recursive function invocation is lost. It should be:
return BFS(newVec, currLevel+1, level, pos);
You should pay attention to compilation warnings. In this case compiler should've definitely complained about "missing return in function returning non-void" or something similar.

To find height of a binary search tree

/*
* To find the Height of a BST tree
*/
public void findHeight(){
if(this.root == null){
System.out.println("BST Tree is Empty ");
}
else
findHeight(this.root);
}
public int findHeight(Tnode temp){
if(temp == null){
System.out.println("BST Tree is Empty ");
return -1;
}
else{
return 1 + Math.max(findHeight(temp.getLeft()) ,findHeight(temp.getRight()) ) ;
}
}
Program is running infinitely.Not able to find the reason , It would be helpfull ,if some one guides me
Thanks in advance
Are you sure the findHeight() function doesn't return anything? Are you expecting anything from that function? Posting more code would help.
"BST Tree is Empty" will also be printed at every terminal leaf of the tree.
To find out what's going on, you could add some debugging output:
private spaces(int len){
String s = " ";
while (s.Length < len) {
s += " ";
}
return s.substring(0, len);
}
public int findHeight(Tnode temp, int nesting, String msg){
String margin = spaces(2*nesting);
if(temp == null){
System.out.println(margin + msg + ": no sub-tree to explore");
return -1;
}
else{
System.out.println(margin + msg);
int hl = findHeight(temp.getLeft(), nesting + 1, "left");
int hr = findHeight(temp.getRight(), nesting + 1, "right");
return 1 + (hl >= hr ? hl : hr) ;
}
}
Your endless recursion might be due to some error in your tree structure. If your left/right child references are never null, the recursion won't terminate.