2012-11-11 313 views
0

我的导师对打印二叉树的方式有特定的输出要求。 他希望的输出是像这样:在二叉搜索树中打印左右子树

根{left_subtree} - {right_subtree}

即:

12 {18} - {24}

18 {6} - - {14}

6 {NULL} - {NULL}

等...

直到今天我都没有意识到这一点,我已经很兴奋,我得到了我的计划工作。

template<class elemType> 
struct nodeType 
{ 
    elemType info; 
    nodeType<elemType> *lLink; 
    nodeType<elemType> *rLink; 
}; 

template<class elemType> 
void bSearchTreeType<elemType>::printPreOrder(nodeType<elemType> *root1) 
{ 
    if(root1 != NULL) { 
     cout<<root1->info<<" "<<"{"<<root1->lLink<<"}"<<endl;//this is where I get the errors 
     printPreOrder(root1->lLink); 
     printPreOrder(root1->rlink); 
    } 
} 

template <class elemType>void bSearchTreeType<elemType>::insert(const elemType& insertItem){ 

    nodeType<elemType> *current; //pointer to traverse the tree 
    nodeType<elemType> *trailCurrent; //pointer behind current 
    nodeType<elemType> *newNode; //pointer to create the node 

    newNode = new nodeType<elemType>; newNode->info = insertItem; 
    newNode->lLink = NULL; 
    newNode->rLink = NULL; 


    if (root1 == NULL) 
     root1 = newNode; 
    else { 
     current = root1; 
     while (current != NULL) 
     { 
      trailCurrent = current; 
      if (current->info == insertItem) 
      { 
       cout << "The item to be inserted is already "; 
       cout << "in the tree -- duplicates are not allowed." << endl; 
       return;   
      } 
      else if (current->info > insertItem) 
       current = current->lLink; 
      else 
       current = current->rLink; 
     }//end while 

     if (trailCurrent->info >insertItem) 
      trailCurrent->lLink = newNode;  
     else 
      trailCurrent->rLink = newNode;  
    } 
} 

我该如何让我的函数打印出左边的子树和右边的子树。每次我尝试一些事情时,我都会得到分段错误或输出奇怪的内存地址。

我在寻找指导和帮助,从伪代码到如何做到这一切都将是非常棒的。我只是困惑

编辑:要包括插入功能,我做什么时,我得到了错误

+0

你'printPreOrder'看起来不错。什么是你的插入方法的实现?你是否总是将lLink,rLink设置为NULL? – PiotrNycz

+0

当我插入 – Craig

+2

时,lLink和rLink确实设置为NULL,告诉我们完整的示例,当您有段错误和/或其他错误时。 – PiotrNycz

回答

1

您可以尝试的东西沿着这些路线:

template<class elemType> 
void bSearchTreeType<elemType>::printPreOrder(nodeType<elemType> *root) { 
    if(root) { 
     cout << root->info << " " << endl; 

     cout << "{"; 
     if(root->left) { 
      cout << root->left->info; 
     } 
     else { 
      cout << "NULL"; 
     } 
     cout << "} -- "; 

     cout << "{"; 
     if(root->right) { 
      cout << root->right->info; 
     } 
     else { 
      cout << "NULL"; 
     } 
     cout << "}"; 

     cout << endl; 

     printPreOrder(root->left); 

     printPreOrder(root->right); 
    } 
} 
+0

没关系,左边只是l链接和右边只是rLink ...我认为 – Craig

+0

非常感谢你 – Craig

+0

这个解决方案不会为空树打印{NULL}并为每个非根节点打印加倍的信息... – PiotrNycz