2014-02-22 107 views
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; 
} 

回答

2

,直到您已经阅读所有的数字不打印任何东西。

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

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

当我尝试我的Inorder根本不打印? – user3335367

+0

尝试输入无效数字,或按Ctrl-D(Linux)或Ctrl-Z(Windows)以触发EOF。你需要循环退出。 –