Could anyone please check why my code is giving Runtime error for the test case which has been provided below.
Question
I have just used a custom sort function which check for the digits of each number and returns true or false accordingly. The code is easy to understand by looking at it.
#include <stack>
#include <algorithm>
void solve(BinaryTreeNode<int>* root,vector<int>& ans) {
if(root==NULL)
return;
ans.push_back(root->data);
solve(root->left,ans);
solve(root->right,ans);
}
bool cmp(const int& num1,const int& num2) {
vector<int> d1,d2;
int n1 = num1,n2=num2;
while(n1!=0) {
d1.push_back(n1%10);
n1/=10;
}
while(n2!=0) {
d2.push_back(n2%10);
n2/=10;
}
if(d1.size()==0) d1.push_back(0);
if(d2.size()==0) d2.push_back(0);
while(d1.size()!=0 && d2.size()!=0) {
if(d1.back()==d2.back()) {
d1.pop_back();d2.pop_back();
}
else
return d1.back()>d2.back();
}
if(d1.size()==0) return true;
return false;
}
void printLargest(BinaryTreeNode<int>* root) {
vector<int> ans;
solve(root,ans);
if(root==NULL)
return;
sort(ans.begin(),ans.end(),cmp);
if(ans[0]==0) {
cout << 0 << endl;return;
}
for(int i=0;i<ans.size();i++)
cout << ans[i];
cout << endl;
}
Test Case on which Runtime error is occuring:-
1
0 1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 -1 -1 -1 -1