user3335367
user3335367

Reputation: 495

Problems printing out my binary tree

I am having difficulty printing out an Inorder binary tree. When I run my program and enter my input, it prints the Inorder after each character.

For example, if I enter ABCD, it will print:

Inorder: A

Inorder: AB

Inorder: ABC

Inorder: ABCD

However I only want to print out that last line.

This is the code that I have:

#include <iostream>
using namespace std;

template <class T>
class BinaryTree
{
    private:
        struct TreeNode
        {
            TreeNode *left;
            TreeNode *right;
            T data;
        };
        TreeNode *root;

    public:

        BinaryTree()
        {
            root = NULL;
        }

        void Inorder(TreeNode *n)
        {
            if(n != NULL)
            {
                Inorder(n -> left);
                cout<< n -> data;
                Inorder(n -> right);
            }
        }

        void PrintInorder()
        {
           Inorder(root);
        }        

        void InsertData(T data)
        {
            TreeNode *t = new TreeNode;
            TreeNode *parent;
            t -> data = data;
            t -> left = NULL;
            t -> right = NULL;
            parent = NULL;

            //is this a new tree?
            if (isEmpty())
                root = t;
            else
            {
               TreeNode *curr;
               curr = root;
               while(curr)
               {
                   parent = curr;
                   if (t -> data > curr -> data)
                        curr = curr -> right;
                   else
                        curr = curr -> left;
               }
               if(t -> data < parent -> data)
                    parent -> left = t;
               else
                    parent -> right =t;
            }
        }

        bool isEmpty()
        {
            return (root == NULL);
        }
};

int main()
{
    BinaryTree <char> BT;
    char num;
    while (cin >> num)
    {
        BT.InsertData(num);

        cout << "Inorder: ";
        BT.PrintInorder();
        cout << endl;      
    }
    return 0;
}

Upvotes: 1

Views: 88

Answers (1)

John Kugelman
John Kugelman

Reputation: 361565

Don't print anything until you've read all the numbers.

while (cin >> num)
{
    BT.InsertData(num);
}

cout << "Inorder: ";
BT.PrintInorder();
cout << endl;      

Upvotes: 2

Related Questions