Search code examples
c++binary-search-treewhitespacepostorder

Remove space from last number in C++


I trying to write a program about reconstruct a binary search tree from inorder and preorder traversal, then output the tree into postorder , I need to remove blank space after the last element from my tree is printed, but I not really sure how to do it.

My postorder code:

    void postorder(Node* root) 
{
    if (root == nullptr) {
        return;
    }
    postorder(root->left);
    postorder(root->right);
    cout << root->data << " ";
}

Suppose output is 4_5_2_3_1, where _ is blank space between numbers (" "), but now my output is 4_5_2_3_1_ (an extra space after 1), how can I remove it?


Solution

  • bool postorder(Node* root) 
    {
        if (!root) {
            return false;
        }
        if (postorder(root->left))
            cout << " ";
        if (postorder(root->right))
            cout << " ";
        return (cout << root->data);
    }