已知二叉树以二叉链表存储,编写算法完成:对于树种每个元素值为x的结点,删除以它为根的子树,并释放相应的空间
#include <iostream>
#include <queue>
typedef struct treenode{
char data;
struct treenode *left;
struct treenode *right;
}treenode,*ptreenode;
ptreenode buytreenode(char x)
{
ptreenode n=(ptreenode) malloc(sizeof (treenode));
n->data=x;
n->left= nullptr,n->right= nullptr;
return n;
}
ptreenode build_tree()
{
ptreenode root= buytreenode('A');
root->left= buytreenode('B');
root->right= buytreenode('C');
root->left->left= buytreenode('D');
root->left->right= buytreenode('E');
root->right->left= buytreenode('F');
root->right->right= buytreenode('G');
root->left->left->left= buytreenode('H');
root->left->left->right= buytreenode('I');
return root;
}
void free_tree(ptreenode root)//后序释放节点
{
if(root== nullptr) return;
free_tree(root->left);
free_tree(root->right);
free(root);
}
ptreenode free_x(ptreenode root,char x)
{
if(root== nullptr) return nullptr;
if(root->data==x) {
free_tree(root);
return nullptr;
}
root->left=free_x(root->left,x);
root->right=free_x(root->right,x);
}
void print_tree(ptreenode root)
{
std::queue<ptreenode > tmp;
tmp.push(root);
int s=tmp.size();
while(!tmp.empty())
{
ptreenode t=tmp.front();
tmp.pop();
s--;
printf("%3c",t->data);
if(t->left) tmp.push(t->left);
if(t->right) tmp.push(t->right);
if (s==0) puts(""),s=tmp.size();
}
}
int main() {
ptreenode root=build_tree();
print_tree(root);
ptreenode tmp= free_x(root,'B');
puts("");
print_tree(tmp);
return 0;
}