The following is a recursive heapify function for an array based priority queue/binary heap.
Can anybody tell me why I'm going into an infinite recursion?
private static void heapify(int i){
if(i < b_heap.size()/2){
int left = i * 2;
int right = left++;
if(b_heap.get(i).getP() > b_heap.get(left).getP()){
swap(i,left);
}
if(b_heap.get(i).getP() > b_heap.get(right).getP()){
swap(i,right);
}
heapify(i++);
heapify(i+2);
}
else{
return;
}
}
ok so I fixed the infinite loop, but the function still doesn't heapify correctly.
here is the new code,
private static void heapify(int i){
DecimalFormat df = new DecimalFormat("0.00");
if(i < b_heap.size()/2){
int left = i * 2;
int right = i * 2 +1;
if(b_heap.get(i).getP() > b_heap.get(left).getP()){
swap(i,left);
}
if(b_heap.get(i).getP() > b_heap.get(right).getP()){
swap(i,right);
}
i++;
heapify(i);
}
else{
return;
}
}
Related
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;
}
Apologies for the basic question, I'm new to java and have been stuck on this for days.
I need firstly to convert letters to numbers and then using recursion to get the sum of those numbers. I think I am close but I'm also aware it very messy
public static void main(String[] arg) {
String str= "11";
//////////////////////////
String s = "helloworld";
String t = "";
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
if (!t.isEmpty()) {
t += " ";
}
int n = (int)ch - (int)'a' + 1;
t += String.valueOf(n);
}
System.out.println(t);
//////////////////////////////
int sum=0;
int x=Integer.parseInt(t);
int y=recursion(x);
System.out.println("The Sum of the digits is: "+ y);
}
public static int recursion(int y) {
if(y/10>=1) {
int tempvar =y%10;
int remain=y/10;
return tempvar + recursion(remain);
}
else {
return y;
}
}}
Ok so first of all, this line: int x=Integer.parseInt(t); will crash the program in runtime because the string t has spaces in it. So you need to remove this:
if (!t.isEmpty()) {
t += " ";
}
Second, parsing the string t to int is a problem, because the number in string t can get like very, very large. Parsing this very..very large number to an int will also produce an exception during runtime. So a better way to do this is leaving it as a string, loop over it and just add the digits in it.
I have two solutions here:
I loop on t and add the digits.
I assume you have some constraint on the size of t so as it can be parsed to int (or long), and then use recursion as you want.
public class Main {
public static void main(String[] args) {
String s = "hew";
String t = "";
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
int n = (int)ch - (int)'a' + 1;
t += String.valueOf(n);
}
System.out.println("t: "+t);
System.out.println("sum using string: " + getSumUsingString(t));
System.out.println("sum using int: " + getSumUsingLong(Long.parseLong(t), 0));
}
// the string function
private static long getSumUsingString(String t) {
long sum = 0;
for (int i = 0; i < t.length(); i++) {
sum += t.charAt(i)-48;
}
return sum;
}
// recursive function
private static long getSumUsingLong(long num, long sum) {
if (num==0) return sum;
sum += num % 10;
return getSumUsingLong(num / 10, sum);
}
}
Note:
You can use for example, BigInteger class in Java to deal with very large numbers if you really need to parse this string t to a number.
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;
}
In a long assignment I found a miraculous behaviour of cout!!
`
for(i=0; i<ndel; i++)
{
cin>>a;
head=Delete(head, a);
cout<<"Deleting ";
cout<<a<<endl;
//cout<<"Deleting "<<a<<endl; /*this gives seg error*/
printInts(head);
}
`
The code works fine with
cout<<a<<endl;
but gives a segmentation fault with
cout<<"Deleting "<<a<<endl;
Here's my Delete function:
node* Delete(node *T, int a)
{
if(a==1 && T!=NULL)
{
T->flag=0;
return T;
}
int arr[50];
int n, i, tr_num; /* tr_num is the index of array corresponding to last node not to be deleted if the no. to be del is leaf*/
node *tr, *ptr; /*tr istracker on last pointer that cannot be deleted if it encounters leaf*/
node *pth[50];
n=find_binary(arr, a);
tr=T;
ptr=T;
pth[0]=T;
tr_num=0;
for(i=0; i<n-1; i++)
{
if(arr[n-2-i]==0)
{
if(ptr->left==NULL)
{
return T;
}
ptr=ptr->left;
pth[i+1]=ptr;
if((ptr->flag==1 && (ptr->right!=NULL || ptr->left!=NULL)) || (ptr->right!=NULL && ptr->left!=NULL))
{
tr_num=i+1;
tr=ptr;
}
}
if(arr[n-2-i]==1)
{
if(ptr->right==NULL)
{
return T;
}
ptr=ptr->right;
pth[i+1]=ptr;
if((ptr->flag==1 && (ptr->right!=NULL || ptr->left!=NULL)) || (ptr->right!=NULL && ptr->left!=NULL))
{
tr_num=i+1;
tr=ptr;
}
}
}
ptr->flag=0;
if(ptr->left==NULL && ptr->right==NULL)
{
for(i=n-1; i>=tr_num+1; i--)
{
delete pth[i];
pth[i]=NULL;
}
if(arr[n-tr_num-2]==1)
{
pth[tr_num]->right=NULL;
}
else if(arr[n-tr_num-2]==0)
{
pth[tr_num]->left=NULL;
}
}
return T;
}
Here's the find binary code..
int find_binary(int arr[], int num)
{
int i=0;
while(num!=0)
{
arr[i]=num%2;
num=num/2;
i++;
}
return i;
}
In another instance:
I have a function with prototype
node * search(node *T, int a);
calling this function in main
cout<<search(BT, 7);
works!
But
node *ptr=search(BT, 7);
gives segmentation error!! I am clueless why, because the similar assignment works completely fine in my delete function but in main it gives segmentation error!!
Note: node is a structure.
I compile using g++
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;
}