I am trying to solve the question:
Given a binary tree, print all the root to leaf paths.
I think I have understood the logic that I need to implement, but my code it is not giving the desired output.
Example
For this tree:
           1
         /   \
        2     3
       / \   / \
      4   5 6   7
The expected output is:
1 2 4
1 2 5
1 3 6
1 3 7
But my code outputs this:
4
2 5
1 6
1 3 7
Code
My C++ code below:
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
struct node {
    int data;
    struct node* left;
    struct node* right;
};
vector <int> ans;
struct node* newnode(int data)
{
    struct node* temp=(struct node*)malloc(sizeof(struct node));
    temp->data=data;
    temp->left=NULL;
    temp->right=NULL;
    return temp;
}
void root_to_leaf_path(struct node* root)
{
    if(root==NULL)
        return;
    root_to_leaf_path(root->left);
    ans.push_back(root->data);
    if(root->left==NULL && root->right==NULL)
    {
        int n=ans.size();
        for(int i=0;i<n;i++)
        {
            cout<<ans[i]<<" ";
        }
        cout<<endl;
    }
    root_to_leaf_path(root->right);
    ans.pop_back();
}
int main()
{
    struct node* root=newnode(1);
    struct node* p1=newnode(2);
    struct node* p2=newnode(3);
    struct node* p3=newnode(4);
    struct node* p4=newnode(5);
    struct node* p5=newnode(6);
    struct node* p6=newnode(7);
    root->left=p1;
    root->right=p2;
    p1->left=p3;
    p1->right=p4;
    p2->left=p5;
    p2->right=p6;
    root_to_leaf_path(root);
}
Where is the mistake?
 
    