0

我已经上下检查了,我的二叉树的实现似乎是正确的,并且适用于用 /* */ 注释掉的实现,但是对于我的 int main while 循环,插入不会插入并将值存储在根目录(第一个值)并检查它是否将值存储在函数中,但第二次调用再次显示其为空。你能解释一下我的主文件与二叉树有关的问题吗?我将不胜感激!

-> http://ideone.com/w9Aa1w (我的功能实现与注释代码工作)

using namespace std;
int choice = 6;
string value;
int main(void)
 {
  //not working implentation

   while(choice != 5){

  //binary tree test
    cout << "Enter 1 to insert " << endl;
    cout << "Enter 2 to search " << endl;
    cout << "Enter 3 to display tree " << endl;
    cout << "Enter 4 to delete tree " << endl;
    cout << "Enter 5 to exit.. " << endl;
       Tree<std::string> B;
    cout << "Your choice -> : " << endl;
    cin >> choice;

 if(choice == 1)
 {
        cout << "Enter value to insert: ";
         cin >> value;
        cout << endl;
        cout << "Inserting new node! " << endl;
        B.insertTree(value);
 }

 if(choice == 2)
 {   
        cout << "Enter value to search: ";
         cin >> value;
        cout << endl;
        cout << "Search for value..." << endl;
        B.searchTree();

  if(choice == 3)
  {    
       cout << "Displaying tree data" << endl;
       B.displayTree();
  }
  if(choice == 4)
  {
       cout << "Deleting tree data" << endl;
       B.deleteTree();     
  }                    
   if(choice == 5)
   cout << "exiting..." << endl;          
  }

    /* //Working part of program seperate function**********

Tree<std::string> tree;
    tree.insertTree(std::string("Hello"));
    tree.insertTree(std::string("World"));

    Tree<std::string>::node* node = tree.searchTree("World");

    cout << node << endl;

     return 0; */
4

1 回答 1

4

您的树B在循环的每次迭代中都超出了范围。

while(choice != 5){
   //...
   Tree<std::string> B;
   //...
}

您需要移动它,使其在运行期间保持在范围内:

Tree<std::string> B;

while(choice != 5){
   //...
   //...
}
于 2013-10-10T19:31:35.333 回答