I wrote code but there is slight error right tree not getting printed
please suggest solution to this
test case 8 10 1 -1 -1 6 9 -1 -1 7 -1 -1 3 -1 14 13 -1 -1 -1
Printing all root to leaf nodes path
Hey @coderajay03 tell me the name of the problem, also please give a brief about your implementation so that i can debug it for you.
no specific name
print all root to leaf nodes paths
I am just using the preorder traversal and storing the result in vector whenever on last node pop one element and insert new path
This is the dry run of your program as you can see that when we traverse on node 3, line number 56 condition i.e,
if(root->left==NULL || root->right==NULL){
return;
}
comes and you return back from there therefore not printing subtree from root of 3 node.
In dry run numbers represent the conditions you have coded in your program and down arrow means traversing downward and upward arrow is for return statement.
how to fix this keeping the same code???
With this implementation you can’t fix it, you have to make some changes cause in the tree you have build if you make a right child of number 1 and let it be x. Then also this problem will occur cause of that return statement only.
Do this that when:
void print(node* node, int path[], int LengthOfPath)
{
if (node == NULL)
return;
//appending the node to the path array
path[LengthOfPath] = node->data;
LengthOfPath++; //increasing length of path too
//it's a leaf, so print the path that led you to here
if (node->left == NULL && node->right == NULL)
{
// Print your Path as you are having your path in path[] array and length of it will be LengthOfPath.
}
else
{
/// otherwise have to try both subtrees
print(node->left, path, LengthOfPath);
print(node->right, path, LengthOfPath);
}
}
Your LengthOfPath should start from 0 and path array should be global to avoid garbage value.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.