王道数据结构p149——10
代码
#include<stdio.h>
#include<stdlib.h>
typedef struct treenode{
char data;
struct treenode *lchild,*rchild;
}treenode,*tree;
//ABD##E##C## //ABD##E##CF##G##
void create(tree &t);
void find_k(tree &t,int k);
void printtree(tree t);
int i = 0;
int main(){
tree T;
create(T);
int k = 5;
find_k(T,k);
//printtree(T);
return 0;
}
void find_k(tree &t,int k){
if(t){
i++;
if(k == i) printf("%c ",t->data);
find_k(t->lchild,k);
find_k(t->rchild,k);
}
}
void printtree(tree t){
if(t){
printf("%c ",t->data);
printtree(t->lchild);
printtree(t->rchild);
}
}
void create(tree &t){
char c;
c = getchar();
if(c == '#') t = NULL;
else{
t = (treenode*)malloc(sizeof(treenode));
t->data = c;
t->lchild = NULL;
t->rchild = NULL;
create(t->lchild);
create(t->rchild);
}
}
注,要添加一个全局变量i,通过i与k的比较,实现输出