USING GLOBAL VECTOR
vector<int> r;
vector<int> inorderTraversal(TreeNode* root) {
if(root==NULL)
return r;
inorderTraversal(root->left);
r.push_back(root->val);
inorderTraversal(root->right);
return r;
}
I am getting answer for all test cases but when using below code I am getting answer when running separately but when I finally submit test cases are failing(input of empty tree) like I am getting Output for some other input why is this happenning?
vector<int> inorderTraversal(TreeNode* root) {
static vector<int> r;
if(root==NULL)
return r;
inorderTraversal(root->left);
r.push_back(root->val);
inorderTraversal(root->right);
return r;
}
If you say the first version works, then I assume your "global" variable is actually an instance variable of a class. In that case that variable is a new variable every time the test suite creates a new instance of the class.
A static local variable however will retain its value even when the function is executed on a new instance of the class of which it is a method.
A solution is to not make it static, and then overload the method, so it can take that r as second parameter:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> r;
return inorderTraversal(root, r);
}
vector<int> inorderTraversal(TreeNode* root, vector<int> r) {
if(root==NULL)
return r;
inorderTraversal(root->left, r);
r.push_back(root->val);
inorderTraversal(root->right, r);
return r;
}
Related
I was trying to store my pre order traversal in a vector.
First i tried this.
vector<int> s;
vector <int> preorder(Node* root)
{
if(root==NULL)
return s;
s.push_back(root->data);
preorder(root->left);
preorder(root->right);
return s;
}
And it gave me wrong answer but later when i tried this
void pre(Node* root,vector<int>& s)
{
if(root==NULL)
return;
s.push_back(root->data);
pre(root->left,s);
pre(root->right,s);
}
vector <int> preorder(Node* root)
{
vector<int> s;
pre(root,s);
return s;
}
I got correct answer.I am not getting why my first code was giving me WA.
(How can i do this in one function?)
I was asked to write a recursive function to print a singly linked list. But my instructor told me that you can not use static variables or arguments in the function. Is recursion really possible without arguments and static variables?
void recursivePrint() const;
Yes, it is possible. Since recursivePrint() is a member function, you merely have to print the value at the head, and then recursively print the rest of the list:
void recursivePrint() const {
if (!head) {
return;
}
std::cout << head->value << " ";
if (head->next) {
head->next->recursivePrint();
}
}
I am having values in vector<uint2> results (size) I just wanna copy the values of results.y alone to a vector<int> count (size). How can I do this using thrust::transform function?
You need to declare some kind of function object (it can be either UnaryFunction or BinaryFunction that will select second element from uint2. You can use lambda if you enable --expt-extended-lambda in nvcc:
auto selector = [&] __device__ (const uint2& pair) { return pair.y; };
You can use function object instead:
struct Selector
{
__host__ __device__ unsigned int operator()(const uint2& pair)
{
return pair.y;
}
};
And then use it in thrust::transform:
thrust::transform(results.begin(), results.end(), count.begin(), selector);
or
Selector selectorObject;
thrust::transform(results.begin(), results.end(), count.begin(), selectorObject);
I am sorry this question is hopelessly vague, but I have a MWE that does not work as I hoped it would (distilled down from a more complex problem I actually wanted to solve, so don't pooh-pooh it as being a toy.). First the Rcpp code:
// accumulate # of non-na elements seen on the input iterator.
void accum_nonna(RVector<double>::const_iterator vecit,
RVector<double>::const_iterator end,
RVector<int>::iterator xret) {
for (;vecit != end;++vecit) {
if (! NumericVector::is_na(*vecit)) { *xret += 1; }
}
}
struct MWE : public Worker
{
// source vector
const RVector<double> input;
// accumulated value
RVector<int> output;
// constructors
MWE(const NumericVector input, IntegerVector output) : input(input), output(output) {}
MWE(const MWE& mwes, Split) : input(mwes.input), output(mwes.output) {}
// accumulate just the element of the range I have been asked to
void operator()(std::size_t begin, std::size_t end) {
accum_nonna(input.begin() + begin, input.begin() + end, output.begin());
}
// join my value with that of another MWE
void join(const MWE& rhs) {
output[0] += rhs.output[0];
}
};
// [[Rcpp::export]]
IntegerVector dumbCount(NumericVector x) {
// allocate the output
IntegerVector output(1);
// declare the instance
MWE mwes(x,output);
// call parallel_reduce to start the work
parallelReduce(0, x.length(), mwes, 5000);
// return the computed number of non-na elements
return output;
}
As far as the user can see, you get a silly function in R called dumbCount that counts the number of non-NA elements in the input vector. It seems to work fine when the input is under the grain size of 5000, but does not work when over it:
> source('mwe.cpp')
> dumbCount(rnorm(4995))
[1] 4995
> dumbCount(rnorm(5005))
[1] 7112
Clearly I have done something that is not threadsafe.
I would suspect the join operation, but I noticed that when I change the code in operator() to output[0] = end - begin; (to solve a different toy problem) I get an entirely different failure mode in that the join does not seem to actually work, rather dumbCount(rnorm(5001)) returns 2501 fairly consistently.
In the following code, I'm trying to get a better hand at understanding how recursion actually work. I've always been a bit confused about it's actual working. I want to know what value does the inorder() function actually return in every step. From where does it get these values of 0,0,11,0,0,11,12,0,0,11 respectively. Could someone tell me the logic? It's a basic inorder tree traversal program.The reason why I'm trying to understand these outputs is because the same logic is somehow used to find the depth of the tree( I think) where with every recursion the value of depth increases without initialization.
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node* newNode(int data)
{
struct node* node=(struct node*)malloc(sizeof(struct node));
node->data=data;
node->left=NULL;
node->right=NULL;
return node;
}
int inorder(struct node *temp) {
if (temp != NULL) {
printf("\nleft %d\n",inorder(temp->left));
printf("\n%d\n", temp->data);
printf("\nright %d\n",inorder(temp->right));
}
}
int main()
{
struct node *root=newNode(1);
root->left=newNode(2);
root->right=newNode(3);
root->left->left=newNode(4);
root->left->right=newNode(5);
inorder(root);
getchar();
return 0;
}
This function should be changed to the following (the first and last print in the original code will only get you more confused!):
int inorder(struct node *temp) {
if (temp != NULL) {
inorder(temp->left);
printf("%d\n", temp->data);
inorder(temp->right);
}
}
The recursion starts with the left branch of a specific node (usually the "root") - printing recursively (in-order) all the nodes on that left-branch, then printing the current node, moving on to printing recursively (in-order) all the nodes in the right branch.
By the way, if you want to keep that tree "ordered" (meaning, all the nodes on the left branch are smaller than the node, and all the nodes on the right branch are bigger or equal to the node) you should change:
root->left->left=newNode(4);
root->left->right=newNode(5);
to:
root->right->right=newNode(4);
root->right->right->right=newNode(5);