Why is the stringstream variable not taking my second input?

  binary-tree, c++, queue, stringstream

Node class with 1 default constructor :-

class Node
{
public:
    int data;
    Node* left, * right;

    Node(const int data = 0)
    {
        left = right = nullptr;
        this->data = data;
    }
};

main function to test if create_tree is working :-

int main()
{
    std::cout << "enter the elements of the tree.n";
    std::string s{};
    getline(std::cin, s);
    std::stringstream ss{};
    ss << s;
    std::queue<std::string> q;
    Node* root{ new Node() };

    while (ss.good())
    {
        ss >> s;
        q.push(s);
    }

    create_tree(root, q);

    std::cout << "root = " << root->data << "n";
    std::cout << "root->right = " << root->right->data << "n";

    return 0;
}

function to create binary tree by taking root node & a string queue q :-

void create_tree(Node*& root, std::queue<std::string> q)
{
    std::queue<Node*> ptr;

    if (q.empty() || q.front() == "N")
    {
        root = nullptr;
        return;
    }

    std::stringstream ss{};
    ss << q.front() << " ";                             //ss << q.front();
    q.pop();
    ss >> root->data;
    ptr.push(root);

    while (!q.empty() && !ptr.empty())
    {
        if (q.front() != "N")
        {
            ptr.front()->left = new Node();
            ss << q.front() << " ";                     //ss << " " << q.front();
            ss >> ptr.front()->left->data;
            ptr.push(ptr.front()->left);
        }

        q.pop();

        if (!q.empty())
        {
            if (q.front() != "N")
            {
                ptr.front()->right = new Node();
                ss << q.front() << " ";                 //ss << " " << q.front();
                ss >> ptr.front()->right->data;
                ptr.push(ptr.front()->right);
            }
            
            q.pop();
        }

        ptr.pop();
    }
}

INPUT is given in Level-order with integers & ‘N’. ‘N’ is used to represent that no further branching will take place in that Node.

INPUT :-

1 2 3

DESIRED OUTPUT :-

root = 1
root->right = 3

in create_tree, if i replace the statements (which has comments in its right) with the commented statements, the program is not working. when the program is inside create_tree; ss is not taking any values inside the while loop. i want to know why?

Source: Windows Questions C++

LEAVE A COMMENT