6_41_递归求出二叉树先序遍历第k个节点的元素的值

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct node
{
    int data;
    struct node*lchild,*rchild;
}tnode,*tree;
tree creat()
{
    int x;
    tree t;
    scanf("%d",&x);
    if(x==0)t=NULL;
    else
    {
        t=(tnode*)malloc(sizeof(tnode));
        t->data=x;
        t->lchild=creat();
        t->rchild=creat();
    }
    return t;
}
int TreeNum(tree t,int *k)
{
    if(t)
    {
        (*k)--;if(*k==0)return t->data;
        if(*k!=0)return TreeNum(t->lchild,k);
        if(*k!=0)return TreeNum(t->rchild,k);
    }
    return -1;
}
int main()
{
    int n;
    tree t=creat();
    printf("input a number:\t\n");
    scanf("%d",&n);
    printf("%d\n",TreeNum(t,&n));
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-04-25 16:13  Thereisnospon  阅读(494)  评论(0编辑  收藏  举报