Click here to Skip to main content
15,881,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
here is my main program
#include <stdio.h>
#include "tree.h"
#include <stdlib.h>

int menu(void);

int main (void){

What I have tried:

This program works but lets say if a tree has the nodes, 1 2 3 4 5 6 7, and the user inputs to delete the number 8, I need it to display a message saying that that number does not exist within the tree
Posted
Updated 26-Nov-22 9:01am
v3

1 solution

Trees can be traversed in many ways, mostly used are: Inorder, Preorder and Postorder.

Following breakdown of steps would help:
1. Use one of the tree traversal methods and check if the current node matches with the node you are searching for.
2. If found, delete the node and stop traversing further
3. If the tree is completely traversed and none of the node matched then display Node not found.

C++
// Using preorder traversal
bool checkIfNodeExists(struct Node* node, int key)
{
    // empty node/nothing to search in
    if (node == NULL)
        return false;
    
    // node found
    if (node->data == key)
        return true;
 
    // recurrsion on left subtree 
    bool resultLeft = checkIfNodeExists(node->left, key);
    if(resultLeft) 
      return true;
 
    // recurrsion on right subtree
    bool resultRight = checkIfNodeExists(node->right, key);
    if(resultRight) 
      return true;

    // node not found
    return false;
}
Quote:
void delete_tree(binarytree *tree, int val)
Your method looks way too complicated. You should extract the common logics out of it.

This method should pass the node you are searching to delete to the checkIfNodeExists method and based on the result, take an action of deleting or messaging (if not found). This would make it easier for you to see where you might be missing something and need to make change.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900