#include<iostream>
#include<stdlib.h>
// 定义二叉树节点结构体
typedef struct TB {
struct TB* lchild; // 左子树指针
struct TB* rchild; // 右子树指针
int data; // 节点数据
} BTnode, *BTree;
// 先序遍历方式将指定节点置空的函数
void Kong(BTree &T, int item) {
BTree s[99], p = T;
int top = -1;
s[0] = p;
// 如果根节点就是目标节点,直接将树置空
if (p->data == item) {
T = NULL;
return;
}
// 利用栈辅助先序遍历
while (p || top!= -1) {
while (p) {
s[++top] = p;
p = p->lchild;
}
p = s[top--];
// 检查左子树是否为目标节点
if (p->lchild) {
if (p->lchild->data == item) {
p->lchild = NULL;
}
}
// 检查右子树是否为目标节点
if (p->rchild) {
if (p->rchild->data == item) {
p->rchild = NULL;
}
}
p = p->rchild;
}
}
// 层次遍历二叉树的函数
void Cenci5(BTree T) {
BTree p = T, q, s[99];
int front = 0, last = 1, level = 0, index = 0;
s[front] = p;
// 层次遍历
while (front < last) {
while (front <= index) {
p = s[front++];
std::cout << p->data;
if (p->lchild) s[last++] = p->lchild;
if (p->rchild) s[last++] = p->rchild;
}
std::cout << "\n";
index = last - 1;
level++;
}
}
int main() {
// 动态分配内存创建二叉树
BTree T = (BTree)malloc(sizeof(BTnode)), t1, t2, t3, t4, t5;
T->data = 0;
T->lchild = (BTree)malloc(sizeof(BTnode));
T->rchild = (BTree)malloc(sizeof(BTnode));
t1 = T->lchild;
t2 = T->rchild;
t1->data = 1;
t2->data = 2;
t1->lchild = NULL;
t1->rchild = NULL;
t2->lchild = (BTree)malloc(sizeof(BTnode));
t2->rchild = (BTree)malloc(sizeof(BTnode));
t3 = t2->lchild;
t4 = t2->rchild;
t3->data = 3;
t4->data = 4;
t3->lchild = NULL;
t3->rchild = NULL;
t4->lchild = NULL;
t4->rchild = NULL;
// 输出置空前的层次遍历
std::cout << "置空前:\n";
Cenci5(T);
// 调用函数将指定节点置空
Kong(T, 2);
// 输出置空后的层次遍历
std::cout << "置空后:\n";
Cenci5(T);
return 0;
}
main()函数中构建的二叉树:
运行结果: