簡體   English   中英

打印我的二叉樹時出現問題

[英]Problems printing out my binary tree

我很難打印出有序的二叉樹。 當我運行程序並輸入輸入時,它會在每個字符后打印命令。

例如,如果我輸入ABCD,它將打印:

順序:A

順序:AB

順序:ABC

順序: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;
}

閱讀完所有數字之前,請勿打印任何內容。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM