编写递归算法,在二叉树中求位于先序序列中第k个位置的结点的值。
二叉链表类型定义:
typedef struct BiTNode {
TElemType data;
BiTNode *lchild, *rchild;
} BiTNode, *BiTree; 实现函数如下:
TElemType GetElemType(BiTree bt,int &num,TElemType &e){
if(bt){
if(num == 1){
e = bt -> data;
return 0;
}else{
if(bt -> lchild){
--num;
GetElemType(bt -> lchild, num, e);
}
if(bt -> rchild){
--num;
GetElemType(bt -> rchild, num, e);
}
}
}
}
TElemType PreOrder(BiTree bt, int k)
/* bt is the root node of a binary linked list, */
/* Preorder travel it and find the node whose */
/* position number is k, and return its value. */
/* if can't found it, then return '#'. */
{
TElemType e;
e = '#';
GetElemType(bt, k, e);
return e;
}
|