#include<iostream>
#include<stdlib.h>
// 定义二叉树节点结构体
typedef struct TB {
struct TB* lchild; // 左子树指针
struct TB* rchild; // 右子树指针
int data; // 节点数据
} BTnode, *BTree;
// 后序非递归方式求节点所在层次函数
int houqiu(BTree T, int item) {
BTree p = T, q, s1[99];
int s2[99], flag, top = -1;
// 当树非空或栈非空时循环
while (p || top!= -1) {
// 沿左子树路径将节点入栈,并标记为第一次访问
while (p) {
s1[++top] = p;
s2[top] = 0;
p = p->lchild;
}
// 取出栈顶节点和访问标记
p = s1[top];
flag = s2[top--];
// 如果是第一次访问该节点
if (flag == 0) {
// 重新入栈并标记为第二次访问,然后处理右子树
s2[top + 1] = 1;
s1[++top] = p;
p = p->rchild;
} else {
// 如果找到目标节点,返回其所在层次
if (item == p->data) {
return top + 2;
}
p = p->rchild;
}
}
return -1; // 如果未找到目标节点
}
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;
// 调用函数查找节点所在层次并输出
printf("%d", houqiu(T, 1));
return 0;
}
main()中创建的二叉树为:
运行结果: