简体   繁体   中英

Recursion stack in Binary search tree

I am trying to delete a node from a binary search tree. While this function works properly why do we need to set node->m_left or node->m_right to return value of deletenode function itself? It is hard to understand this recursive structure.
currently doing it only for the leaf node

Node<T>*  deletenode(T key){
         return deletenode(key,this->root);
        }
        Node<T>*  deletenode(T key,Node<T>* node){
            Node<T>* temp;
         if(node==nullptr){
             return node;
         }
         if(key<node->m_data){
             node->m_left=deletenode(key,node->m_left);
         }
         if(key>node->m_data){
             node->m_right=deletenode(key,node->m_right);
         }
          
         

         return temp;
        }
        
        

You're setting the left or right to the result of calling the deletenode function on that branch, not to the function itself.

The recursion means: "If my tree has a left branch and a right branch, and the item to delete is in the left branch, then make a new tree that has the same right branch, but the result of removing the item to delete from the left branch as its left branch"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM