2016-08-01 18 views
0

私はバイナリ検索ツリーのデストラクタを作成しています。私はkillがNULLに設定されているときに頭の左のポインタがNULLに設定されることはないので、最初のwhileループで無限ループにぶつかります。これはなぜですか、どうすれば修正できますか?バイナリ検索ツリーのデストラクタ

ありがとうございます!

BST::~BST() 
{ 
    Node* kill = head; 
    /* 
    While-loop runs until all of head's left branch has been deleted 
    */ 
    while(head->get_left() != NULL) 
    { 

     kill = head->get_left();//Set the pointer variable kill to heads left node. 

     /* 
     While-loop moves the kill pointer to a bottom node with that has no children 
     */ 
     while(kill->get_left() != NULL && kill->get_right() != NULL) 
     { 
      if(kill->get_left() != NULL) 
      { 
       kill = kill->get_left(); 
      } 
      if(kill->get_right() != NULL) 
      { 
       kill = kill->get_right(); 
      } 
     } 

     delete kill;//deletes the bottom node with no children 
     kill = NULL; 
    } 

    kill = head; 
    /* 
    While-loop runs until all of head's right branch has been deleted 
    */ 
    while(head->get_right() != NULL) 
    { 

     kill = head->get_right();//Sets the kill pointer to head's right node 

     /* 
     While-loop moves the kill pointer to a bottom node with no children 
     */ 
     while(kill->get_left() != NULL && kill->get_right() != NULL) 
     { 
      if(kill->get_left() != NULL) 
      { 
       kill = kill->get_left(); 
      } 
      if(kill->get_right() != NULL) 
      { 
       kill = kill->get_right(); 
      } 
     } 

     delete kill;//deletes the bottom node with no children 
     kill = NULL; 


    } 

    delete kill;//deletes the head node 



} 
+1

[MCVE]してください、いつものように。 –

答えて

2

デストラクタを簡略化できるようです。 Nodeのデストラクタを実装します。この場合

Node::~Node() 
{ 
    delete left; 
    left = NULL; 
    delete right; 
    right = NULL; 
} 

あなたBST::~BST()は次のようになります:このような何か

BST::~BST() 
{ 
    delete head; 
    head = NULL; 
} 
+2

'nullptr'への影響は不要です。 'std :: unique_ptr'を使うと、この単純化されたコードを避けることさえできます。 – Jarod42