1
我在打印出Inorder二叉樹時遇到困難。當我運行我的程序並輸入我的輸入時,它會在每個字符後打印Inorder。打印出二進制樹的問題
例如,如果我輸入ABCD,它將打印:
中序:一個
中序: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;
}
當我嘗試我的Inorder根本不打印? – user3335367
嘗試輸入無效數字,或按Ctrl-D(Linux)或Ctrl-Z(Windows)以觸發EOF。你需要循環退出。 –