简体   繁体   中英

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;
}

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM