数据结构复习笔记(递归先序遍历)

来源:互联网 发布:玉溪广电网络分公司 编辑:程序博客网 时间:2024/06/05 22:45

6.41③ 编写递归算法,在二叉树中求位于先序序列中
第k个位置的结点的值。

要求实现下列函数:
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 '#'.          */

二叉链表类型定义:
typedef struct BiTNode {
    TElemType data;
    BiTNode  *lchild, *rchild;
} BiTNode, *BiTree;

 

BiTree Pre(BiTree b, int &j)
{
 BiTree p;
 if(!b||j==1)
    return b;
 j=j-1;  
 p=Pre(b->lchild,j);
 if(!p)
    return Pre(b->rchild,j);
 return p;
}
TElemType PreOrder(BiTree bt, int k)
{    
 BiTree pb=Pre(bt,k);
 if(!pb)   
    return '#';
 return pb->data;
}


原创粉丝点击