1 / 1
Feb 2024

WHY IS THIS GIVING RUNTIME ERROR???

#include
#include <bits/stdc++.h>
using namespace std;

int dp_max[10005][3];
int dp_min[10005][3];

struct node{
int data;
struct node* left;
struct node* right;
};
int maxG(node *root, int col)//0-R, 1-G, 2-B
{
//base conditions
if(root==NULL) return 0;

//memoize
if(dp_max[root->data][col]!=-1) return dp_max[root->data][col];

int maxGreen=0;
if(col==1) maxGreen=1;
if(col==2){
	maxGreen+=max(maxG(root->left,1)+maxG(root->right,0),
	              maxG(root->left,0)+maxG(root->right,1));
}
else if(col==1){
	maxGreen+=max(maxG(root->left,0)+maxG(root->right,2),
	               maxG(root->left,2)+maxG(root->right,0));
}
else if(col==0){
	maxGreen+=max(maxG(root->left,1)+maxG(root->right,2),
	              maxG(root->left,2)+maxG(root->right,1));
}

return dp_max[root->data][col]=maxGreen;

}

int minG(node *root, int col)//0-R, 1-G, 2-B
{
//base conditions
if(root==NULL) return 0;

//memoize
if(dp_min[root->data][col]!=-1) return dp_min[root->data][col];

int minGreen=0;
if(col==1) minGreen=1;
if(col==2){
	minGreen+=min(minG(root->left,1)+minG(root->right,0),
	              minG(root->left,0)+minG(root->right,1));
}
else if(col==1){
	minGreen+=min(minG(root->left,0)+minG(root->right,2),
	               minG(root->left,2)+minG(root->right,0));
}
else if(col==0){
	minGreen+=min(minG(root->left,1)+minG(root->right,2),
	              minG(root->left,2)+minG(root->right,1));
}

return dp_min[root->data][col]=minGreen;

}

int ind=0;
node* creTree(string str){
char ch = str[ind];
node * root = new node;
root->data = ind++;
if(ch==‘2’){ //means it has 2 child
root->left = creTree(str);
root->right = creTree(str);
}
else if(ch==‘1’){ //means it has one child
root->left = creTree(str);
}
else { // 0 child or also called as leaf node
root->left = root->right = NULL;
}
return root;
}

int main() {
int t; cin>>t;
while(t–){
memset(dp_max,-1,sizeof(dp_max)); //node,color
memset(dp_min,-1,sizeof(dp_min)); //node,color
string s; cin>>s;
node * root = creTree(s);

int maxi = max(maxG(root,0),max(maxG(root,1),maxG(root,2)));
int mini = min(minG(root,0),max(minG(root,1),minG(root,2)));
cout<<maxi<<" "<<mini<<"\n";
}

}