2016-08-01 111 views
0

我正在製作二叉搜索樹的析構函數。我用第一個while循環打了一個無限循環,因爲當kill設置爲NULL時,head的左指針永遠不會設置爲NULL。爲什麼會這樣,我該如何解決它?二叉搜索樹的析構函數

在此先感謝!

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