打印我的二叉树时出现问题

时间:2014-02-22 00:52:09

标签: c++ binary-tree

我无法打印出Inorder二叉树。当我运行我的程序并输入我的输入时,它会在每个字符后打印Inorder。

例如,如果我输入ABCD,它将打印:

按顺序:A

按顺序:AB

Inorder:ABC

Inorder:ABCD

但是我只想打印出最后一行。

这是我的代码:

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

1 个答案:

答案 0 :(得分:2)

在阅读完所有数字之前,请勿打印任何内容。

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

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