Deleting Leaf Nodes from an Ordered Binary Tree

  • Context:
  • Thread starter Thread starter evinda
  • Start date Start date
  • Tags Tags
    Binary Nodes Tree
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 2K views
evinda
Gold Member
MHB
Messages
3,741
Reaction score
0
Hi! (Nerd)

Given a tree, I want to write an algorithm, that deletes from each node, from the corresponding ordered binary tree, the rightmost child, that is a leaf.

That's what I have tried:

Code:
Algorithm(NODE *P){
   if (P==NULL) return error;
   if (P->RC!=NULL) P=P->RC;
   if (P->LC!=NULL) Algorithm(P->LC);
   if (P->RC==NULL) P->LC->RC=NULL;
   Algorithm(P->RC)

Could you tell me if it is right? :confused:
 
Last edited:
Physics news on Phys.org
I think that there are some mistakes.. But, is it entirely wrong? (Thinking)
 
evinda said:
Given a tree, I want to write an algorithm, that deletes from each node, from the corresponding ordered binary tree, the rightmost child, that is a leaf.
Code:
Algorithm(NODE *P){
   if (P==NULL) return error;
   if (P->RC!=NULL) P=P->RC;
   if (P->LC!=NULL) Algorithm(P->LC);
   if (P->RC==NULL) P->LC->RC=NULL;
   Algorithm(P->RC)

evinda said:
I think that there are some mistakes.. But, is it entirely wrong? (Thinking)

Hi! (Happy)

You have the set up for a recursive algorithm, which includes a check for the final condition, and recursive calls.
Good! (Smile)

Code:
   if (P==NULL) return error;

What is the reason that you think this results in an error? (Wondering)
Code:
   if (P->RC!=NULL) P=P->RC;

This seems to break the set up of the recursive function call.
As a result the left sub tree will not be visited any more.
Should it be like that? (Wondering)
Code:
   if (P->LC!=NULL) Algorithm(P->LC);

The check for a NULL pointer seems redundant, since we'll check that in the function anyway. (Nerd)
Code:
   if (P->RC==NULL) P->LC->RC=NULL;

What should this do? :confused:

If there is no child on the right side, set the grand child on the left side to NULL?
That doesn't seem to make sense. (Worried)

Btw, I think deleting a node should involve calling [m]free()[/m]. (Nerd)