Click here to Skip to main content
15,667,536 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
Updated 26-Nov-22 9:01am

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.

// 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);
      return true;
    // recurrsion on right subtree
    bool resultRight = checkIfNodeExists(node->right, key);
      return true;

    // node not found
    return false;
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

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

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