题目:
编写递归算法:求指定结点在给定的二叉树中的层次(根节点为第1层)。约定指定结点不存在,返回0.
二叉链表类型定义如下:
typedef struct BiTNode {
TElemType data;
struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree;
实现:
void xLevel(BiTree T, TElemType x, bool &found, int &xlev) {
// 求二叉树中以值为 x 的结点的层次,结点不存在,返回0;
// found 为判断是否找到的标志符,xlev 为以值为 x 的结点的层次
if (T == NULL) {
return;
}
if (T->data == x) {
found = true;
xlev++;
return;
}
if (!found) {
xLevel(T->lchild, x, found, xlev);
}
if (!found) {
xLevel(T->rchild, x, found, xlev);
}
if (found) {
xlev++;
}
}