I was learning how to delete a binary tree using Postorder traversal. I understand that to delete a node, first we need to delete its child node and then the node itself, so Postorder traversal is the best fit to delete a binary tree. I thought of doing the same using Inorder traversal, everything works fine but I don't understand how the below code works?
#include<stdio.h>
#include<malloc.h>
struct b_tree{
int data;
struct b_tree *left,*right;
};
typedef struct b_tree tree;
tree* create_node(int data)
{
struct b_tree* new_node=(tree*)malloc(sizeof(tree));
new_node->data=data;
new_node->left=NULL;
new_node->right=NULL;
return new_node;
}
void delete_tree(tree *root)
{
if(root==NULL)
return;
delete_tree(root->left);
printf("Deleting %d node.\n",root->data);
free(root);
delete_tree(root->right);
}
int main()
{
tree *root=NULL;
root=create_node(1);
root->left=create_node(2);
root->right=create_node(3);
root->left->left=create_node(4);
root->left->right=create_node(5);
root->left->right->left=create_node(6);
root->left->right->right=create_node(7);
root->right->right=create_node(8);
root->right->right->left=create_node(9);
delete_tree(root);
root=NULL;
return 0;
}

According to Inorder traversal first node to be deleted is 4 and after that 2, but once we freed 2 it should loose all it's data, means it should not retain the pointer to right node as well which is 5, but even after 2 is freed its left child 5 is still traversed but it should not happen because node 2 is already freed.
The output of the above code is:
I was expecting the output to be in the following order of nodes: 4 2 1.
I don't understand how all this is working. Please correct me if I'm wrong.
delete_tree(root->right)to do, if not delete the right subtree? - Andreas Grapentin2is freed, it should loose all its data, which ,means it should also loose pointer to right child as well which is5, but even after freeing2it is still able to access5, how? - Amanshu Kataria