Tree returning the maximum value - recursion

50
/ \
30 70 (( which should return 50+70=120 ))
int MyFunction(struct node *root){
struct node *ptr=root;
int leftsum=0;
int rightsum=0;
if(ptr==NULL){
return;
}
else{
MyFunction(ptr->left);
leftsum=leftsum+ptr->key;
MyFunctipn(ptr->right);
rightsum=rightsum+ptr->key;
return (root->key+max(leftsum,rightsum));
}
}
for that, I've written this code. Maybe it is wrong so please help me as I'm new in this field. I want to write a recursive code such a way that it compares two leaf node(left and right) and returns the maximum to the parent nood.

The recursive function should look something like this:
int getMaxPath(Node* root){
// base case, We traveled beyond a leaf
if(root == NULL){
// 0 doesn't contribute anything to our answer
return 0;
}
// get the max current nodes left and right children
int lsum = getMaxPath(root->left);
int rsum = getMaxPath(root->right);
// return sum of current node value and the maximum from two paths starting with its two child nodes
return root->value + std::max(lsum,rsum);
}
Full code:
#include <iostream>
struct Node{
int value;
Node* left;
Node* right;
Node(int val){
value = val;
left = NULL;
right = NULL;
}
};
// make a tree and return a pointer to it's root
Node* buildTree1(){
/* Build tree like this:
50
/ \
30 70
*/
Node* root= new Node(50);
root->left = new Node(30);
root->right = new Node(70);
}
int getMaxPath(Node* root){
if(root == NULL){
// 0 doesn't contribute anything to our answer
return 0;
}
int lsum = getMaxPath(root->left);
int rsum = getMaxPath(root->right);
return root->value + std::max(lsum,rsum);
}
int main() {
using namespace std;
Node* root = buildTree1();
int ans = getMaxPath(root);
cout<< ans <<endl;
return 0;
}

int Sum(struct node *root)
{
if(root->left == NULL && root->right== NULL)
return root->key;
int lvalue,rvalue;
lvalue=Sum(root->left);
rvalue=Sum(root->right);
return root->key+max(lvalue,rvalue);
}
int max(int r,int j)
{
if(r>j)
return r;
else
return j;
}

Related

When finding cycles in undirected graphs, why can't we just keep track of previous parent node while using BFS traversal

Basically when we use DFS we just check if the adjacent nodes for a newly visited node have been already visited and they are not the parent node which made the DFS call for this node. If this is the case cycle is present.
I was using similar thing for BFS while keeping track of previous parent node and my logic doesn't seem to work. The test case on which my code is failing is too big to understand the problem. Can anyone let me know where my logic is broken? Thank you in advance
bool bfs(vector<int> adj[], bool isVisited[], int s, int V)
{
queue<int> q;
q.push(s);
isVisited[s] = true;
int parent = s;
int prevParent = -1;
while(q.empty() == false)
{
int u = q.front();
prevParent = parent;
parent = u;
q.pop();
for(int i = 0 ; i < adj[u].size() ; i++)
{
if(isVisited[adj[u][i]] == false)
{
isVisited[adj[u][i]] = true;
q.push(adj[u][i]);
// parent[][i]] = u;
}
else
{
if(adj[u][i] != prevParent)
return true;
}
}
}
return false;
}
bool isCycle(int V, vector<int> adj[]) {
// Code here
bool isVisited[V] = {false};
for(int i = 0 ; i < V ; i++)
{
if(isVisited[i] == false)
if(bfs(adj, isVisited, i, V) == true)
{
return true;
}
}
return false;
}

code got strucked in a infinite loop when I tried to reverse a linked list using recursion

I was trying to reverse a linked list using recursion but when I tried to print out all the elements of the linked list at first it was printing out elements as expected but after printing out the last element it started printing the last and second last element repeatedly. I tried to debug it and I think the problem is that the last element is pointing towards the second last element whether it should be pointing towards NULL. I am not able to figure out what is wrong with my code so please help me out.
example- input 1,2,3,4,5,6
expected output 6,5,4,3,2,1
actual output 6,5,4,3,2,1,2,1,2 ...
#include<iostream>
using namespace std;
class node{
public:
int val;
node *next;
node(int val)
{
this->val = val;
this->next = NULL;
}
node(int val,node *next)
{
this->val= val;
this->next=next;
}
};
void insertAtTail(node *&head,int val){
node *n = new node(val);
if (head==NULL)
{
head = n;
return;
}
node *temp = head;
while (temp->next!=NULL)
{
temp = temp->next;
}
temp->next=n;
}
void display(node *head)
{
node *n = head;
while (n!=NULL)
{
cout << n->val << "->";
n = n->next;
}
cout << "NULL" << endl;
}
node* reverseRecursive(node *&head)
{
if (head == NULL || head->next==NULL)
{
return head;
}
node *nHead = reverseRecursive(head->next);
head->next->next = head;
head->next == NULL;
return nHead; // 1->2->3->4->5->6->NULL
}
int main()
{
node *head = NULL;
insertAtTail(head,1);
insertAtTail(head,2);
insertAtTail(head,3);
insertAtTail(head,4);
insertAtTail(head,5);
insertAtTail(head,6);
display(head);
node *newhead = reverseRecursive(head);
display(newhead);
return 0;
}
There is a bug in function reverseRecursive().
Line head->next == NULL; should be head->next = NULL;
node* reverseRecursive(node *&head)
{
if (head == NULL || head->next==NULL)
{
return head;
}
node *nHead = reverseRecursive(head->next);
head->next->next = head;
head->next == NULL; // <<< should be head->next = NULL;
return nHead; // 1->2->3->4->5->6->NULL
}
Not sure which compiler you were using, but this statement will typically generate a warning.

CS50 Pset 5 Hashtable issue

After creating a hash table and assigning each letter to a value for the table, i am noticing the first word output by the table for the beginning of every linked list is the same word. Somehow it seems I am transferring the entire dictionary to each array in the table even though I have attempted to separate them. Any assistance would be awesome! Thanks in advance
// Implements a dictionary's functionality
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include "dictionary.h"
// Represents a node in a hash table
typedef struct node
{
char *word;
struct node *next;
}
node;
// Number of buckets in hash table
const unsigned int N = 25;
// Hash table
node *table[N];
char lowerword[LENGTH+1];
// Returns true if word is in dictionary else false
bool check(const char *word)
{
int bucketfind = 0;
int x = 0;
for (int b = word[x]; b != '\0';b = word[x], x++)
{
int lowertemp = tolower(word[x]);
if (x == 0)
{
bucketfind = lowertemp - 97;
}
char lowerfinal = lowertemp;
lowerword[x] = lowerfinal;
//printf("%c", lowerword[x]);
}
int wordlen = x + 1;
int pr = 0;
while (table[bucketfind] -> next != NULL)
{
int dwlen = strlen(table[bucketfind]-> word);
pr++;
//printf("%i, %i, %s, %i\n", pr, dwlen, table[bucketfind] -> word, bucketfind);
}
//TODO
return false;
}
// Hashes word to a number
unsigned int hash(const char *word)
{
int asciifirst = word[0];
int lowerfirst = tolower(asciifirst);
int bucketnum = lowerfirst - 97;
return bucketnum;
}
// Loads dictionary into memory, returning true if successful else false
int dictwords = 0;
//char *cword = (char*)malloc(sizeof(char)*46);
bool load(const char *dictionary)
{
char *cword = malloc(sizeof(char)*46);
FILE *dict = fopen(dictionary, "r");
if (dictionary == NULL)
{
return false;
}
int x = 0;
while ((fscanf(dict, "%s", cword) != EOF))
{
node *nword = malloc(sizeof(node));
nword -> word = cword;
nword -> next = NULL;
int bucket = hash(cword);
//printf("%i\n", bucket);
if (table[bucket] != NULL)
{
nword -> next = table[bucket];
table[bucket] = nword;
}
else
{
table[bucket]= nword;
}
dictwords++;
}
fclose(dict);
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
return dictwords;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
// TODO
return false;
}
It's not just the first word; every word in the linked list is the same word (the last one read). cword gets 46 bytes of memory at a specific address here char *cword = malloc(sizeof(char)*46);. Every word from dictionary is read into that same address.

Calculating the standard deviation of a linkedlist elements

I wanted to calculate the standard deviation of a inked list elements,so I wrote a function to calculate both the average and the sum and then claculate the standard deviation by the formula , but I am getting error " 0xC0000005: Access violation reading location 0x00000000."at the line 46 ,
sd += ((first->info)-average)*((first->info-average);
Why this problem occurs and is there any way to get rid of it ?
My code is as follows :
class Node
{
public:
int info;
Node* next;
int value;
};
class List:public Node
{
Node *first,*last;
public:
List()
{
first=NULL;
last=NULL;
}
void create();
void insert();
void delet();
void display();
void search();
void sum();
void sd();
};
void List::sd()
{
system("cls");
cout<<"The Linked List Operations Program";
cout<<"\n==========================================================="<<endl;
Node *temp=first;
int sd = 0;
int length=0;
while(temp!=NULL)
{
length++;
temp=temp->next;
}
int sum = 0;
while (first != NULL)
{
sum += first->info;
first = first->next;
}
int average;
average = (sum/length);
sd += ((first->info)-average)*((first->info-average);
first=first->next;
cout<<average;
cout<<"The standard diviation is " <<sqrt(sd)/10 ;
cin.get();
cin.get();
}
int main()
{
system("cls");
int m;
List l;
Node *first;
int ch;
l.sd();
return 0 ;
}
void List::create()
{
system("cls");
cout<<"The Linked List Operations Program";
cout<<"\n==========================================================="<<endl;
Node *temp;
temp=new Node;
int n;
cout<<"\nEnter an element to create the first node of the linkedlist:";
cin>>n;
temp->info=n;
temp->next=NULL;
if(first==NULL)
{
first=temp;
last=first;
}
else
{
last->next=temp;
last=temp;
}
}
void List::insert()
{
system("cls");
cout<<"The Linked List Operations Program";
cout<<"\n==========================================================="<<endl;
Node *prev,*cur;
prev=NULL;
cur=first;
int count=1,pos,ch,n;
Node *temp=new Node;
cout<<endl<<"ADDED";
system("cls");
temp->info=rand();
temp->next=NULL;
last->next=temp;
last=temp;
}

Infinite loop : Process not terminating properly

struct node
{
int data;
node* left;
node* right;
};
int secondlargest(struct node* a)
{
while(a->right != NULL){
secondlargest(a->right);
}
return a->data;
}
I am not able to trace where have I done the mistake and why its not coming out of the while loop.
Your mistake is that you shouldn't use an while but instead an if because it is recursive, but what do you want the function to return? the data of the last member? if so it should be like this:
int secondlargest(struct node* a) {
if(a == NULL) return -1;
secondlargestr(a);
}
int secondlargestr(struct node* a) {
if(a->right!=NULL) return secondlargest(a->right);
return (a->data);
}
If you insist on the recursive version, change the while to if.
int secondlargest(node* a)
{
if(a == null){
// if the first node is already NULL
return -1;
}
if(a->right == NULL){
return a->data;
}else{
return secondlargest(a->right);
}
}
Basics of recursion:
Must have base case
Break down problem size recursively
If you want the iterative way:
int secondlargest(node* a)
{
node* temp = a;
int data = -1;
while(temp != null){
data = temp->data;
temp = temp->right;
}
return data;
}

Resources