2012-11-11 227 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