#include<stdio.h>
#include<stdlib.h>
typedef struct TreeNode
{
int data;
struct TreeNode* left, *right;
}TNode,*BTree;
void PreOrder(BTree T)
{
if (T != NULL)
{
printf("%d ", T->data);
PreOrder(T->left);
PreOrder(T->right);
}
else
printf("NULL ");
}
//先释放左右子树,再释放根结点,才能保证完全释放,故一定是后序遍历
void DeleteIt(BTree& T)
{
if (T != NULL)
{
DeleteIt(T->left);
DeleteIt(T->right);
printf("删除的是:%d\n ", T->data);
free(T);
T = NULL;//这里要置空。
}
}
//先序遍历到值为x的子树的根结点,将其删除
//否则就继续遍历
//由于对树进行删改,要用引用类型
void PreOrder2(BTree& T, int x)
{
if (T != NULL)
{
if (T->data == x)
DeleteIt(T);
else
{
PreOrder2(T->left, x);
PreOrder2(T->right, x);
}
}
}
int main()
{
//首先在这里创建一棵完全二叉树,之前的博客有写,欢迎查看
int x;
scanf("%d", &x);
PreOrder2(tree, x);
//先序遍历,看看是否释放正确
PreOrder(tree);
return 0;
}